factory 0.1.24: a session continued after Claude Code compaction reaches Factory (#66)

* factory 0.1.23: a resumed turn's restored skills reach Factory wherever they sit

#68 took 0.1.22, so this moves to 0.1.23.

Claude Code 2.1.292 session 1a2063e5 is the turn Factory answered 403.
Its transcript renders the post-compaction attachments, in order, as system
reminders: a token marker, a restored Read and its result, an omitted-file
note, the invoked-skills reminder, the agent-type list, MCP server
instructions, the environment paragraph and the model line. No token marker
follows the skills reminder. The snapshot's contextRendering is "announced",
so the same paragraphs also travel unwrapped in one system turn. The request
bytes were not in the routing log; the fixture is those rendered paragraphs,
unwrapped, in that order.

announcedContext used to reassemble the reminder only when a token marker
came right after it, and then treated everything up to that marker as skill
text. A reminder at the end of the turn, or followed by a Read, the
environment or a hook, kept the refused opening. A reminder with other
attachments and a later token swallowed those attachments into the skill
encoding.

The refused part is the fixed opening plus the complete IMPORTANT paragraph.
That complete reminder is rephrased wherever it sits. Skill text now ends at
the next paragraph the adapter already knows (token marker, hook, restored
Read, omitted-file note, Read result, environment, model line, skill-list
header, changed-file note, agent-type list, MCP instructions) or at the end
of the turn. Those following paragraphs stay themselves and are adapted on
their own. A second pass is byte-for-byte. Quoted fragments, an incomplete
IMPORTANT paragraph, a hook that owns the reminder and assistant content stay
untouched.

0.1.22 was not tried against Factory: the installed copy stayed 0.1.21, and
this change was not sent to Factory either.

Run: HOME set to an empty temp dir, bun test packages/factory: 120 pass,
0 fail. node --check packages/factory/index.mjs, bun scripts/check.mjs
factory, and git diff --check are clean. The new test covers the captured
order plus a reminder at the end of the turn, a reminder followed by Read,
environment and a hook, and a quoted skill body. Fetch is stubbed.

* factory 0.1.23: restored skills open a resumed turn without token metadata

A resumed turn can start with the complete invoked-skills reminder when no
files were restored and totalTokensReminder is off. restoredContext now
recognizes its exact opening and IMPORTANT paragraph through the existing
invokedSkillsMatch and attachment boundaries. A restored-file opening can
also use the complete skills reminder as evidence when it ends the turn.
Adapted openings, incomplete reminders, quotations and hook-owned output
retain their existing behavior.

Cover no-token system turns and folded user text on inference and token
counting, including standalone reminders, trailing tokens, omitted-file and
Read prefixes, exact skill decoding, cache metadata and byte-for-byte second
passes. Each of the six boundaries missing independent regression coverage
now follows a quoted skill directly. README documents the no-token forms.

Run with HOME set to an empty temporary directory: bun test packages/factory,
121 pass, 0 fail. node --check packages/factory/index.mjs,
bun scripts/check.mjs factory and git diff --check pass.
Removing each of the omitted-note, Read-result, model, skill-list, MCP and
changed-file boundaries makes the new independent regression test fail.
The whole-project test suite is left to CI. Fetch is stubbed; no request was
sent to a real Factory account.

* factory 0.1.24: main already published 0.1.23 (#71), so this change takes the next version

#71 shipped factory 0.1.23 while this PR waited, so npm has 0.1.23. This
only moves the version, so the squash publishes as 0.1.24.

Run: merged onto main a885a16, HOME=<scratch> bun test packages/factory:
124 pass, 0 fail; bun scripts/check.mjs: all pass.

---------

Co-authored-by: chenguoqing <chenguoqing@kemai.cn>
Co-authored-by: yetone <yetoneful@gmail.com>
This commit is contained in:
guoqchen1001
2026-10-13 09:05:49 +08:00
committed by GitHub
co-authored by chenguoqing yetone
parent a885a16190
commit 86b4760f55
4 changed files with 354 additions and 17 deletions
+24 -8
View File
@@ -129,10 +129,23 @@ continuation instructions; context without those phrases stays verbatim.
Complete generated reminders for restored Read calls and omitted files are
adapted too. Read arguments and file paths are preserved; quoted or incomplete
reminders are left alone.
Claude Code (2.1.291 and later) also restores skills invoked before compaction
as one generated reminder. Factory refuses that fixed opening, and the restored
skill text can quote the same client phrases as tool output. A complete
reminder has its opening sentence rephrased. When its skill text quotes a
refused phrase, that text is encoded as a JSON string with explicit skill-text
decoding instructions; decoding restores the skill text exactly. Skill text
without those phrases stays verbatim inside the rephrased reminder. Pasted
fragments and incomplete reminders are left untouched.
Claude Code can also combine reminders into a token-prefixed `system` turn
without the reminder wrappers. The adapter handles the known metadata
paragraphs in that form, including skill-list updates, while retaining
numbered file contents, token markers and SessionStart hook output.
paragraphs in that form, including skill-list updates and complete
invoked-skills reminders. A complete reminder is the fixed opening sentence
followed by the complete `IMPORTANT:` paragraph; skill text then runs until
the next known attachment (a token marker, hook, restored Read, omitted-file
note, Read result, environment, model line, skill-list header, changed-file
note, agent-type list or MCP server instructions) or the end of the turn.
Numbered file contents, token markers and SessionStart hook output stay.
The same adaptation applies when a translating gateway folds that complete
token-prefixed block into a user message.
Standalone skill updates can instead start with the generated skill-list
@@ -148,12 +161,15 @@ 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.
runtime context as one turn that opens with an unwrapped restored-file note,
Read call or complete invoked-skills reminder, with no token marker first.
A complete skills reminder is recognized even when no files were restored
and no environment or token paragraph follows it. A restored-file opening
requires the generated environment paragraph, a token marker or a complete
skills reminder before any hook output. Each fixed paragraph (file notes,
Read calls and results, skills, 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
+74 -8
View File
@@ -736,6 +736,22 @@ function announcedContext(text, start = 1) {
// Any hook owns its file snippets. Non-startup hooks do not stop the
// existing adaptation of model/environment metadata that follows them.
if (HOOK_NOTIFICATION.test(hook)) quoteChangedFiles = false
// Invoked skills span several paragraphs. The refused text is the fixed
// opening plus the complete IMPORTANT paragraph; skill bodies follow
// until the next attachment this adapter already knows. A token marker
// after the reminder is not required: Claude Code emits one after a tool
// result or a user prompt, and the restored reminder usually sits among
// other attachments. Keep skill text out of the paragraph adapter,
// including on a second pass.
if (part.startsWith(INVOKED_SKILLS_OPENING + " ") || part.startsWith(INVOKED_SKILLS_COMPAT + " ")) {
let end = i + 1
while (end < parts.length && !invokedSkillsBoundary(parts[end])) end++
const wrapped = open + parts.slice(i, end).join("\n\n") + close
if (invokedSkillsMatch(wrapped)) {
parts.splice(i, end - i, invokedSkills(wrapped).slice(open.length, -close.length))
continue
}
}
const changedFile = quoteChangedFiles ? changedFileText(part) : null
if (changedFile !== null) {
parts[i] = changedFile
@@ -763,19 +779,30 @@ function announcedContext(text, start = 1) {
// 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.
// opening and the generated environment paragraph, a token marker or a
// complete invoked-skills reminder before the first hook. When no file was
// restored, that complete skills reminder can itself open the turn. Each
// paragraph is adapted as in a token-prefixed bundle, the rest kept
// byte-for-byte. An adapted block no longer has its generated opening,
// 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 = "<system-reminder>\n" + (result < 0 ? parts[0] : parts[0].slice(0, result)) + "\n</system-reminder>"
if (!COMPACT_FILE.test(opening) && !COMPACT_READ.test(opening)) return null
if (compactContext(opening) === opening) return null
for (const part of parts.slice(1)) {
const file = COMPACT_FILE.test(opening) || COMPACT_READ.test(opening)
if (!file && !parts[0].startsWith(INVOKED_SKILLS_OPENING + " ")) return null
if (file && compactContext(opening) === opening) return null
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
if (HOOK_NOTIFICATION.test(part.replace(/^<system-reminder>\n/, ""))) return null
if (SYSTEM_ENV_CONTEXT.test(part + "\n") || /^<total_tokens>\d+ tokens left<\/total_tokens>$/.test(part)) return announcedContext(text, 0)
if (part.startsWith(INVOKED_SKILLS_OPENING + " ")) {
let end = i + 1
while (end < parts.length && !invokedSkillsBoundary(parts[end])) end++
const wrapped = "<system-reminder>\n" + parts.slice(i, end).join("\n\n") + "\n</system-reminder>"
if (invokedSkillsMatch(wrapped)) return announcedContext(text, 0)
if (!file) return null
}
if (i > 0 && (SYSTEM_ENV_CONTEXT.test(part + "\n") || /^<total_tokens>\d+ tokens left<\/total_tokens>$/.test(part))) return announcedContext(text, 0)
}
return null
}
@@ -816,6 +843,43 @@ function systemModelLine(text) {
const INSTRUCTIONS_REMINDER = "<system-reminder>\nCodebase and user instructions are shown below"
const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all projects)"
// Claude Code (2.1.291 and later) restores skills invoked before compaction
// as one generated reminder. Factory refuses that fixed opening, and the restored
// skill text can quote the same client phrases tool output does. Keep the
// remaining instructions and encode only a complete reminder whose body
// quotes them. Pasted fragments and clean skill bodies stay verbatim.
const INVOKED_SKILLS_OPENING = "The following skills were invoked EARLIER in this session (before the conversation was compacted), not on the current turn."
const INVOKED_SKILLS_COMPAT = "Skills invoked earlier in this session are listed below for context."
const INVOKED_SKILLS_REMINDER = /^<system-reminder>\nThe following skills were invoked EARLIER in this session \(before the conversation was compacted\), not on the current turn\. They are shown here for context only so you remain aware of their guidelines\.\n\nIMPORTANT: Do NOT re-execute these skills or perform their one-time setup actions \(e\.g\., scheduling, creating files\) again\. Any request or argument text embedded in the skill bodies below — for example under a "## User Request" or "## Input" heading — was captured when that skill was first invoked\. It is NOT the user's current message and NOT a new request: do not act on it as if it were live\. Only continue to apply ongoing behavioral guidelines from these skills where still relevant\.\n\n([\s\S]*)\n<\/system-reminder>$/
// The next paragraph of a bundle that already belongs to another attachment.
// Skill text ends here, so a following Read, environment or hook stays its
// own paragraph. A skill body that merely quotes one of these stays inside.
function invokedSkillsBoundary(part) {
if (SYSTEM_TOKEN_CONTEXT.test(part) || part.startsWith("<total_tokens>") || HOOK_NOTIFICATION.test(part)) return true
if (part.startsWith("Called the Read tool with the following input: ")) return true
if (part.startsWith("Note: ") && part.includes(" was read before the last conversation was summarized")) return true
if (part.startsWith("Result of calling the Read tool:\n")) return true
if (SYSTEM_ENV_CONTEXT.test(part + "\n") || SYSTEM_ENV_UPDATE.test(part + "\n")) return true
if (SYSTEM_MODEL_UPDATE.test(part)) return true
if (part === "The following skills are available for use with the Skill tool:") return true
if (part.startsWith("Available agent types for the Agent tool:")) return true
if (part.startsWith("# MCP Server Instructions")) return true
if (CHANGED_FILE_HEADER.test(part)) return true
return false
}
function invokedSkillsMatch(text) {
const opening = "<system-reminder>\n" + INVOKED_SKILLS_COMPAT
const generated = text.startsWith(opening) ? "<system-reminder>\n" + INVOKED_SKILLS_OPENING + text.slice(opening.length) : text
return generated.match(INVOKED_SKILLS_REMINDER)
}
function invokedSkills(text) {
const match = invokedSkillsMatch(text)
if (!match) return text
const quoted = quotedToolText(match[1], "Skill text encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n")
const head = text.slice(0, text.length - match[1].length - "\n</system-reminder>".length)
return head.replace(INVOKED_SKILLS_OPENING, INVOKED_SKILLS_COMPAT) + quoted + "\n</system-reminder>"
}
// Factory returns 403 for Claude Code's fixed compaction opening, even
// without tools or other history. Match the two generated opening sentences,
// including the provenance prefix, without requiring a Summary label. Keep
@@ -849,6 +913,8 @@ function compactContext(text, quoteChangedFiles = true) {
}
const summary = piSummary(text)
if (summary !== text) return summary
const skills = invokedSkills(text)
if (skills !== text) return skills
const read = text.match(COMPACT_READ)
if (read) {
try {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-factory-auth",
"version": "0.1.23",
"version": "0.1.24",
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
"type": "module",
"main": "./index.mjs",
+255
View File
@@ -10,6 +10,9 @@ const configSkill = '- update-config: Use this skill to configure the Claude Cod
const skillReminder = "<system-reminder>\nThe following skills are available for use with the Skill tool:\n\n" + configSkill + "\n- custom: Keep every user-defined skill description intact.\n</system-reminder>"
// Claude Code 2.1.292's edited_text_file attachment (also present in 2.1.284).
const changedFileHeader = "Note: /tmp/history.jsonl changed on disk since you last read it. That's usually deliberate, so take it as the current state rather than reverting it; if the change looks wrong, say so rather than undoing it yourself — otherwise no need to call it out. Here are the relevant changes (shown with line numbers):\n"
// Claude Code's invoked_skills attachment template, present since 2.1.291.
const invokedSkillsOpening = "The following skills were invoked EARLIER in this session (before the conversation was compacted), not on the current turn."
const invokedSkillsPreamble = "They are shown here for context only so you remain aware of their guidelines.\n\nIMPORTANT: Do NOT re-execute these skills or perform their one-time setup actions (e.g., scheduling, creating files) again. Any request or argument text embedded in the skill bodies below — for example under a \"## User Request\" or \"## Input\" heading — was captured when that skill was first invoked. It is NOT the user's current message and NOT a new request: do not act on it as if it were live. Only continue to apply ongoing behavioral guidelines from these skills where still relevant.\n\n"
async function loaded() {
const seen = []
@@ -915,6 +918,258 @@ test("leaves quoted compaction text, incomplete wrappers and non-user content un
expect(seen[0].body).toBe(body)
})
test("adapts the post-compaction invoked-skills reminder and quotes refused phrases in its body", async () => {
const { l, seen } = await loaded()
const opening = invokedSkillsOpening
const preamble = invokedSkillsPreamble
const clean = "### Skill: notes\nPath: userSettings:notes\n\nKeep 中文 and this skill's own instructions."
const quoted = "### Skill: identity\nPath: userSettings:identity\n\nThe skill quotes: You are Claude Code, Anthropic's official CLI for Claude.\nKeep /tmp/示例.jsonl and a literal \\u0054."
const head = "<system-reminder>\n" + opening + " " + preamble
const nested = clean + "\n\nQuoted example:\n<system-reminder>\nSkills invoked earlier in this session are listed below for context.\n</system-reminder>\n\n" + opening
for (const body of [clean, nested, quoted]) {
const text = head + body + "\n</system-reminder>"
for (const endpoint of [url, url + "/count_tokens"]) {
for (const content of [text, [{ type: "text", text, cache_control: { type: "ephemeral" } }, { type: "text", text: "Continue the task." }]]) {
const request = { system: droid, messages: [{ role: "user", content }] }
await l.fetch(endpoint, { method: "POST", body: JSON.stringify(request) })
const got = JSON.parse(seen.at(-1).body).messages[0].content
const out = typeof got === "string" ? got : got[0].text
expect(out).toStartWith("<system-reminder>\nSkills invoked earlier in this session are listed below for context. " + preamble)
expect(out).toEndWith("\n</system-reminder>")
expect(out).not.toStartWith("<system-reminder>\n" + opening)
const restored = out.slice(out.indexOf(preamble) + preamble.length, -"\n</system-reminder>".length)
if (body !== quoted) {
expect(restored).toBe(body)
} else {
expect(restored).toStartWith("Skill text encoded as a JSON string.")
expect(restored).not.toContain("You are Claude Code")
expect(JSON.parse(restored.slice(restored.indexOf("\n") + 1))).toBe(body)
}
expect(got).toEqual(typeof content === "string" ? out : [{ ...content[0], text: out }, content[1]])
const once = seen.at(-1).body
await l.fetch(endpoint, { method: "POST", body: once })
expect(seen.at(-1).body).toBe(once)
}
}
}
const pasted = "Why does compaction say:\n" + opening
const partial = "<system-reminder>\n" + opening + " extra text the generator does not add.\n</system-reminder>"
for (const text of [pasted, partial, opening]) {
const body = JSON.stringify({ system: droid, messages: [{ role: "user", content: [{ type: "text", text }] }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
}
})
test("adapts token-prefixed invoked-skills bundles as system turns or folded user text", async () => {
const { l, seen } = await loaded()
const token = "<total_tokens>14831568 tokens left</total_tokens>"
const head = invokedSkillsOpening + " " + invokedSkillsPreamble
const clean = "### Skill: notes\nPath: userSettings:notes\n\nKeep 中文 and this skill's own instructions."
const phrases = [
"You are Claude Code, Anthropic's official CLI for Claude.",
"You have been invoked in the following environment:",
"x-anthropic-billing-header: cc_version=2.1.292;",
"This session is being continued from a previous conversation that ran out of context.",
]
// Skill prose that resembles a model line but is not the generated sentence.
// A complete "You are powered by the model …" paragraph is the model
// attachment and ends the reminder; see the resumed-turn fixture below.
const model = "The skill mentions a model named Example, which is not the runtime model line."
const cleanBody = clean + "\n\n" + model
const bodies = [cleanBody, ...phrases.map((phrase) => clean + "\n\n---\n\n### Skill: identity\nPath: userSettings:identity\n\nThe skill quotes: " + phrase + "\nKeep /tmp/示例.jsonl and a literal \\u0054.\n\n" + model)]
const read = 'Called the Read tool with the following input: {"file_path":"/tmp/file.txt"}'
const adaptedRead = read.replace("Called the Read tool with the following input:", "Previously read file with these arguments:")
const hook = "SessionStart:compact hook success: Keep this hook output exactly.\n\n" + head + clean
for (const skillBody of bodies) {
const text = [token, read, token, head + skillBody, token, hook].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: "Continue the task." }]]) {
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).messages[0].content
const out = typeof got === "string" ? got : got[0].text
const prefix = [token, adaptedRead, token, "Skills invoked earlier in this session are listed below for context. " + invokedSkillsPreamble].join("\n\n")
const suffix = "\n\n" + token + "\n\n" + hook
expect(out).toStartWith(prefix)
expect(out).toEndWith(suffix)
const restored = out.slice(prefix.length, -suffix.length)
if (skillBody === cleanBody) {
expect(restored).toBe(skillBody)
} else {
expect(restored).toStartWith("Skill text encoded as a JSON string.")
for (const phrase of phrases) expect(restored).not.toContain(phrase)
expect(JSON.parse(restored.slice(restored.indexOf("\n") + 1))).toBe(skillBody)
}
const adapted = typeof content === "string" ? out : [{ ...content[0], text: out }, content[1]]
expect(JSON.parse(seen.at(-1).body)).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 invoked-skills bundles", async () => {
const { l, seen } = await loaded()
const token = "<total_tokens>14831568 tokens left</total_tokens>"
const reminder = invokedSkillsOpening + " " + invokedSkillsPreamble + "### Skill: notes\nPath: userSettings:notes\n\nKeep the user's text exactly."
const bundle = [token, reminder, token].join("\n\n")
const values = [
"Explain:\n" + bundle,
[token, "Explain this quoted reminder:\n" + reminder, token].join("\n\n"),
[token, "```text\n" + reminder + "\n```", token].join("\n\n"),
[token, invokedSkillsOpening, token].join("\n\n"),
bundle.replace("IMPORTANT: Do NOT re-execute", "IMPORTANT: Do re-execute"),
bundle.replaceAll("14831568", "unknown"),
[token, "SubagentStart hook additional context: Keep hook output.", reminder, token].join("\n\n"),
"Explain:\n" + reminder,
"```text\n" + reminder + "\n```",
invokedSkillsOpening,
reminder.replace("IMPORTANT: Do NOT re-execute", "IMPORTANT: Do re-execute"),
[reminder.replace("IMPORTANT: Do NOT re-execute", "IMPORTANT: Do re-execute"), "# Environment\nYou have been invoked in the following environment:\n - Platform: win32", token].join("\n\n"),
["SessionStart:compact hook success: Keep hook output.", reminder].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, cache_control: { type: "ephemeral" } }]]) {
const body = JSON.stringify({ system: droid, messages: [{ role, content }] })
await l.fetch(endpoint, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
}
}
}
}
const body = JSON.stringify({ system: droid, messages: [{ role: "assistant", content: bundle }] })
await l.fetch(url, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
})
// Claude Code 2.1.292, session 1a2063e5, the turn that Factory answered 403.
// Attachments render as separate system reminders; contextRendering is
// "announced", so the same bytes also travel unwrapped in one system turn.
// Order after the compact summary: token, restored Read, omitted-file note,
// invoked_skills, agent list, MCP instructions, environment, model line.
// <total_tokens> is not repeated after invoked_skills.
test("adapts the captured post-compaction system turn, wherever the invoked-skills reminder sits", async () => {
const { l, seen } = await loaded()
const token = "<total_tokens>14964378 tokens left</total_tokens>"
const read = 'Called the Read tool with the following input: {"file_path":"C:\\\\Users\\\\CHENGU~1\\\\AppData\\\\Local\\\\Temp\\\\q3up\\\\mr4.py"}\nResult of calling the Read tool:\n1\timport json, subprocess, os, time\n2\tKeep this source.'
const omitted = "Note: C:\\Users\\chenguoqing\\code\\2026Q3总结与Q4计划-草稿.md 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 clean = "### Skill: gitea-mr\nPath: userSettings:gitea-mr\n\nKeep 中文 and this skill's own instructions."
const quoted = clean + "\n\n---\n\n### Skill: identity\nPath: userSettings:identity\n\nThe skill quotes: You are Claude Code, Anthropic's official CLI for Claude.\nKeep /tmp/示例.jsonl."
const agents = "Available agent types for the Agent tool:\n- claude: Catch-all for any task that doesn't fit a more specific agent. (Tools: *)\n\nWhen you launch multiple agents for independent work, send them in a single message with multiple tool uses so they run concurrently."
const mcp = "# MCP Server Instructions\n\nThe following MCP servers have provided instructions for how to use their tools and resources:\n\n## axure-query\nKeep these server instructions."
const environment = "# Environment\nYou have been invoked in the following environment: \n - Primary working directory: C:\\Users\\chenguoqing\\code\\cloudpos-knowledge\n - Platform: win32\n - Shell: bash"
const model = "You are powered by the model named Opus 5.5. The exact model ID is factory/claude-opus-5-5. Assistant knowledge cutoff is June 2026."
const hook = "SessionStart:compact hook success: Keep this hook output exactly."
const head = invokedSkillsOpening + " " + invokedSkillsPreamble
const compat = "Skills invoked earlier in this session are listed below for context. " + invokedSkillsPreamble
const adaptedRead = 'Previously read file with these arguments: {"file_path":"C:\\\\Users\\\\CHENGU~1\\\\AppData\\\\Local\\\\Temp\\\\q3up\\\\mr4.py"}\nResult of calling the Read tool:\n1\timport json, subprocess, os, time\n2\tKeep this source.'
const adaptedOmitted = "Previously read file: C:\\Users\\chenguoqing\\code\\2026Q3总结与Q4计划-草稿.md. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it."
const adaptedEnvironment = environment.replace("# Environment", "# Runtime context").replace("You have been invoked in the following environment:", "The session environment is:")
const adaptedModel = "Current model name: Opus 5.5. Model ID: factory/claude-opus-5-5. Model knowledge cutoff: June 2026."
const shapes = [
["token, reminder, token", [token, head + clean, token], [token, compat + clean, token]],
["token, reminder, incomplete token", [token, head + clean, "<total_tokens>123 tokens left"], [token, compat + clean, "<total_tokens>123 tokens left"]],
["token, reminder (end of turn)", [token, head + clean], [token, compat + clean]],
["token, reminder, Read, environment, hook", [token, head + clean, read, environment, hook], [token, compat + clean, adaptedRead, adaptedEnvironment, hook]],
["token, Read, reminder, environment (end)", [token, read, head + clean, environment], [token, adaptedRead, compat + clean, adaptedEnvironment]],
["token, reminder, Read, environment, token", [token, head + clean, read, environment, token], [token, compat + clean, adaptedRead, adaptedEnvironment, token]],
["captured turn, clean skill", [token, read, omitted, head + clean, agents, mcp, environment, model], [token, adaptedRead, adaptedOmitted, compat + clean, agents, mcp, adaptedEnvironment, adaptedModel]],
["captured turn, quoted skill", [token, read, omitted, head + quoted, agents, mcp, environment, model], null],
["skills first, no token", [head + clean, agents, mcp, environment, model], [compat + clean, agents, mcp, adaptedEnvironment, adaptedModel]],
["skills first, trailing token", [head + clean, agents, environment, model, token], [compat + clean, agents, adaptedEnvironment, adaptedModel, token]],
["skills only", [head + clean], [compat + clean]],
["omitted note, skills (end)", [omitted, head + clean], [adaptedOmitted, compat + clean]],
["Read, skills (end)", [read, head + clean], [adaptedRead, compat + clean]],
// A SessionStart hook stops the scan, so the environment after it stays.
["reminder, then a hook, no token", [token, head + clean, hook, environment], [token, compat + clean, hook, environment]],
]
for (const [name, inputParts, outputParts] of shapes) {
const skillBody = name.includes("quoted") ? quoted : clean
const text = inputParts.join("\n\n")
const expected = outputParts === null ? null : outputParts.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" } }]]) {
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).messages[0].content
const out = typeof got === "string" ? got : got[0].text
expect(out).not.toContain(invokedSkillsOpening)
if (expected !== null) {
expect(out).toBe(expected)
} else {
const encodedAt = out.indexOf("Skill text encoded as a JSON string.")
expect(encodedAt).toBeGreaterThan(0)
const jsonAt = out.indexOf("\n", encodedAt) + 1
const boundary = out.indexOf("\n\nAvailable agent types for the Agent tool:")
expect(JSON.parse(out.slice(jsonAt, boundary))).toBe(skillBody)
expect(out.slice(boundary + 2)).toBe([agents, mcp, adaptedEnvironment, adaptedModel].join("\n\n"))
expect(out).toStartWith([token, adaptedRead, adaptedOmitted, compat.trimEnd()].join("\n\n"))
}
const once = seen.at(-1).body
await l.fetch(endpoint, { method: "POST", body: once })
expect(seen.at(-1).body).toBe(once)
}
}
}
}
})
test("keeps each attachment after quoted invoked skills outside the skill encoding, without a leading token", async () => {
const { l, seen } = await loaded()
const head = invokedSkillsOpening + " " + invokedSkillsPreamble
const compat = "Skills invoked earlier in this session are listed below for context. " + invokedSkillsPreamble
const skill = "### Skill: identity\nPath: userSettings:identity\n\nThe skill quotes: You are Claude Code, Anthropic's official CLI for Claude.\nKeep 中文 and a literal \\u0054."
const prefix = compat + "Skill text encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n"
const omitted = "Note: /tmp/示例.txt 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 model = "You are powered by the model named Opus 5.5. The exact model ID is factory/claude-opus-5-5. Assistant knowledge cutoff is June 2026."
const result = "Result of calling the Read tool:\n1\tKeep ordinary source exactly."
const skillList = "The following skills are available for use with the Skill tool:"
const mcp = "# MCP Server Instructions\n\nKeep the server's instructions."
const changed = changedFileHeader + "1\tOrdinary changed source."
const hook = "SessionStart:compact hook success: Keep this hook output exactly."
const boundaries = [
[[], []],
[[omitted], ["Previously read file: /tmp/示例.txt. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it."]],
[[result], [result]],
[[model], ["Current model name: Opus 5.5. Model ID: factory/claude-opus-5-5. Model knowledge cutoff: June 2026."]],
[[skillList, "- custom: Keep this description."], [skillList, "- custom: Keep this description."]],
[[mcp], [mcp]],
[[changed], [changed]],
[[hook], [hook]],
]
for (const [tail, adaptedTail] of boundaries) {
const text = [head + skill, ...tail].join("\n\n")
const suffix = adaptedTail.length ? "\n\n" + adaptedTail.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" } }]]) {
const request = { system: droid, messages: [{ role, content }] }
await l.fetch(endpoint, { method: "POST", body: JSON.stringify(request) })
const got = JSON.parse(seen.at(-1).body).messages[0].content
const out = typeof got === "string" ? got : got[0].text
expect(out).toStartWith(prefix)
expect(out).toEndWith(suffix)
expect(out).not.toContain("You are Claude Code")
expect(JSON.parse(out.slice(prefix.length, suffix ? -suffix.length : undefined))).toBe(skill)
const adapted = typeof content === "string" ? out : [{ ...content[0], text: out }]
expect(JSON.parse(seen.at(-1).body)).toEqual({ ...request, messages: [{ role, content: adapted }] })
const once = seen.at(-1).body
await l.fetch(endpoint, { method: "POST", body: once })
expect(seen.at(-1).body).toBe(once)
}
}
}
}
})
test("adapts generated compacted file reminders without changing paths, read arguments or file contents", async () => {
const { l, seen } = await loaded()
const args = '{"file_path":"/tmp/示例 file.txt","offset":10,"limit":20}'