Files
plugins/packages/factory/instructions.test.mjs
T
yetone cdf45137d6 factory 0.1.34: Claude Code's re-read instructions reminder reaches Factory after compaction (#243)
zygs1083-dotcom (#243): after compaction, a long Claude Code session went
403 Forbidden on all three Factory accounts. Claude Code renders its
instructions attachment two ways (n_t in 2.1.292 to 2.1.303):

- first copy: "Codebase and user instructions are shown below. …"
- changed copy (changed: true, reason compaction and others):
  "Instruction files were re-read after the conversation was compacted;
  these differ from their earlier copies — each replaces its earlier copy,
  and the instructions preamble above still applies:" (or "These
  instruction files changed — …" without a reason)

Both list "Contents of ~/.claude/CLAUDE.md (user's private global
instructions for all projects):", the phrase Factory refuses (magpie#634).
Only the first opening was matched, so the changed copy went out as it was.

- INSTRUCTIONS_REMINDER matches both openings, requiring the changed
  copy's full sentence and the "Contents of " that follows it. The rename
  is limited to the reminder itself: text joined after its close (chat
  completions' joined user text) stays as written. String user turns on
  /llm/a get it too; before, only text blocks did.
- quotedToolText encodes tool output that quotes the phrase (the
  reporter's session read Claude Code's renderer source and went 403
  from then on), losslessly, as for the other phrases.
- A 403 the plugin rebuilds keeps Factory's request id (x-request-id,
  request-id, x-amzn-requestid, cf-ray, or the body's request_id) and the
  error's code and type in the message, and request_id on the Anthropic
  body. Headers already went back as they came.

The fixtures are the literal texts the 2.1.303 bundle's n_t/Mje/bMr build
and id() wraps; 2.1.301 and 2.1.302 have the same strings, and the
2.1.292 darwin-arm64 npm package has the same sentence pieces.

What was run at this commit:
- bun test packages/factory/: 161 pass, 0 fail.
- bun scripts/check.mjs factory: ok. git diff --check: clean.
- Broken by hand: with the old startsWith-only opening, the 4 changed-
  wrapper tests fail; without the phrase in quotedToolText, the tool-result
  test fails too; with upstreamIds returning nothing, the 403 test fails.
- Not tried: a real Factory request with the changed reminder (no live
  account was used), so that Factory accepts the renamed copy is inferred
  from the first copy's fix in 0.1.12, not seen.
2026-10-19 17:42:37 +08:00

119 lines
7.8 KiB
JavaScript

// plugins#243 (zygs1083-dotcom): Claude Code renders its instructions
// attachment two ways. The first copy opens with the preamble; a copy
// re-read after the files changed (changed: true, reason "compaction" and
// the others) opens with its own sentence. Both name ~/.claude/CLAUDE.md
// "(user's private global instructions for all projects)", which Factory
// refuses (yetone/magpie#634), but only the first copy was adapted, so a
// long session went 403 on every account after compaction.
//
// The texts below are what Claude Code 2.1.303's n_t()/Mje()/bMr() build
// (the same functions as the reporter's 2.1.292), wrapped as id() wraps a
// meta message: "<system-reminder>\n" + text + "\n</system-reminder>".
import { afterEach, expect, test } from "bun:test"
import { FactoryAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const messages = "https://api.factory.ai/api/llm/a/v1/messages"
const chat = "https://api.factory.ai/api/llm/o/v1/chat/completions"
const droid = "You are Droid, an AI software engineering agent built by Factory."
const GLOBAL = "(user's private global instructions for all projects)"
const files = "Contents of /home/u/.claude/CLAUDE.md " + GLOBAL + ":\nUse tabs.\nContents of /tmp/p/CLAUDE.md (project instructions, checked into the codebase):\nRun the tests."
const preamble = "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."
const replaces = " — each replaces its earlier copy, and the instructions preamble above still applies:\n"
const wrap = (t) => "<system-reminder>\n" + t + "\n</system-reminder>"
const WRAPPERS = {
initial: wrap(preamble + "\n" + files),
compaction: wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + files),
"settings sync": wrap("Instruction files were re-read after settings were synced onto this machine; these differ from their earlier copies" + replaces + files),
"no reason": wrap("These instruction files changed" + replaces + files),
"with a removed file": wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + files + "\nInstructions no longer present: /tmp/p/old/CLAUDE.md"),
}
const adapted = (t) => t.replaceAll(GLOBAL, "(global instructions)")
async function loaded(status = 200, reply = '{"id":"ok"}', headers = {}) {
const seen = []
globalThis.fetch = async (url, init) => {
seen.push({ url: String(url), ...init })
return new Response(reply, { status, headers })
}
const auth = { type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" }
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } })
return { l: await hooks.auth.loader(async () => auth), seen }
}
for (const [name, reminder] of Object.entries(WRAPPERS)) {
test(`renames the global CLAUDE.md in the ${name} instructions reminder`, async () => {
const { l, seen } = await loaded()
const pasted = "Why does Claude Code write " + GLOBAL + "?"
// Messages: text blocks, and a string user turn
await l.fetch(messages, { method: "POST", body: JSON.stringify({ system: droid, messages: [{ role: "user", content: [{ type: "text", text: reminder }, { type: "text", text: pasted }] }, { role: "assistant", content: "ok" }, { role: "user", content: reminder }] }) })
const sent = JSON.parse(seen.at(-1).body).messages
expect(sent[0].content[0].text).toBe(adapted(reminder))
expect(sent[0].content[0].text).not.toContain(GLOBAL)
expect(sent[0].content[1].text).toBe(pasted)
expect(sent[2].content).toBe(adapted(reminder))
// chat completions: magpie joins a turn's text blocks into one string
await l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "system", content: droid }, { role: "user", content: reminder + pasted }] }) })
expect(JSON.parse(seen.at(-1).body).messages[1].content).toBe(adapted(reminder) + pasted)
})
}
test("leaves text that only resembles the changed instructions reminder", async () => {
const { l, seen } = await loaded()
const near = [
wrap("These instruction files changed and " + GLOBAL),
"Quoted:\n" + WRAPPERS.compaction,
wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + "Use " + GLOBAL),
]
for (const text of near) {
const body = JSON.stringify({ system: droid, messages: [{ role: "user", content: [{ type: "text", text }] }] })
await l.fetch(messages, { method: "POST", body })
expect(seen.at(-1).body).toBe(body)
}
})
test("losslessly quotes the instructions template when a tool result shows it", async () => {
const { l, seen } = await loaded()
// what reading Claude Code's renderer source puts in the history
const source = 'case"User":return" ' + GLOBAL + '"}}\ns=e.reason?`Instruction files were re-read ${Qj(e.reason)}; these differ from their earlier copies`:"These instruction files changed"\n' + WRAPPERS.compaction
const request = { system: droid, messages: [{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "grep" } }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: source }, { type: "tool_result", tool_use_id: "t2", content: [{ type: "text", text: source }] }] }] }
await l.fetch(messages, { method: "POST", body: JSON.stringify(request) })
const sent = JSON.parse(seen.at(-1).body).messages[1].content
for (const encoded of [sent[0].content, sent[1].content[0].text]) {
expect(encoded).toStartWith("Tool output encoded as a JSON string.")
expect(encoded).not.toContain(GLOBAL)
expect(JSON.parse(encoded.slice(encoded.indexOf("\n") + 1))).toBe(source)
}
// the same on chat completions' tool messages
await l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "system", content: droid }, { role: "tool", tool_call_id: "t1", content: source }] }) })
const tool = JSON.parse(seen.at(-1).body).messages[1].content
expect(tool).not.toContain(GLOBAL)
expect(JSON.parse(tool.slice(tool.indexOf("\n") + 1))).toBe(source)
})
test("a 403 keeps Factory's request id and error code", async () => {
const { l } = await loaded(403, JSON.stringify({ error: { message: "Forbidden", code: "client_rejected", type: "forbidden" } }), { "x-request-id": "req_abc123", "cf-ray": "8f00-SJC" })
const res = await l.fetch(messages, { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "OK" }] }) })
expect(res.status).toBe(403)
expect(res.headers.get("x-request-id")).toBe("req_abc123")
const body = await res.json()
expect(body.request_id).toBe("req_abc123")
expect(body.error.type).toBe("permission_error")
expect(body.error.message).toStartWith("Forbidden (upstream request id req_abc123, code client_rejected, type forbidden) — Factory refused")
// a plain-text 403 with only a ray id says that, on the OpenAI route too
const plain = await loaded(403, "Forbidden", { "cf-ray": "8f00-SJC" })
const res2 = await plain.l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "user", content: "OK" }] }) })
const msg = (await res2.json()).error.message
expect(msg).toStartWith("403 Forbidden: Forbidden (upstream request id 8f00-SJC) — Factory refused")
// nothing to tell: the message is as before
const bare = await loaded(403, "Forbidden")
const res3 = await bare.l.fetch(messages, { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "OK" }] }) })
const b3 = await res3.json()
expect(b3.request_id).toBeUndefined()
expect(b3.error.message).toStartWith("403 Forbidden: Forbidden — Factory refused")
})