跳到主要内容
chapter-06 第二部分 · 可控运行 · 实现笔记

06 · 系统提示词与环境感知

里程碑 → 注入环境后答对"当前分支有什么未提交改动"

第 05 章的 agent 已经能改代码,但它不知道自己在什么项目里。

本章给每次 run 加上一份环境快照:

  • CLI 在每个用户 prompt 之前,读取项目指令和当前的 Git 状态,组装成 system prompt。
  • agent 多了一个 list_files 工具。它不会递归扫描,所以不会因为仓库太大而撑爆输出。

能力边界与控制流

用户输入
  → CLI 读取 CLAUDE.md / cwd / platform / shell / time / git status
  → buildSystemPrompt()
  → runAgent({ system, messages, tools, env })
  → callModel(..., system)

本章守住五条边界:

  • 每个用户 prompt 之前都重新读取环境,不沿用旧的分支和旧的指令。
  • system prompt 按“基础指令 → 项目指令 → 易变环境”的顺序排列。
  • 只读 cwd 根目录下的 CLAUDE.md,最多 32,000 字符。
  • Git 只注入 status --short --branch 的输出,最多 12,000 字符,不注入完整 diff。
  • list_files 只列一层,最多 200 项。权限、流式、重试和取消,继续往后放。

为什么这样排序:稳定的放前面,大的按需拉取

base → 项目指令 → 易变环境 这个顺序,在本章只是把不同来源的内容分层,还没有启用缓存。

到第 11 章真正加入 prompt caching(提示词缓存)时,我们会发现:项目指令也可能被 agent 自己修改。所以到那时,只有 base 留在显式的 cache breakpoint(缓存断点)前面,项目指令和环境改为放进消息,并且只在变化时追加。本章还不能说已经命中了缓存。

环境信息也不应该全部塞进 system。分两类处理:

  • 由 runtime 主动推入:cwd、平台、Git 摘要。它们每轮都常用,体积也有上限。
  • 由模型通过工具拉取:目录和文件内容。它们只是偶尔需要,规模可能很大。

判断放哪一类,看四件事:用得多不多、体积大不大、变得快不快、读取成本高不高。不是“能读到就全部注入”。

仓库里的内容,被当成了可信指令

根目录的 CLAUDE.md 是仓库自己控制的文本,但本实现主动把它提升进了 system。这里明确采用一个假设:用户选择信任当前仓库的指令。

普通文件通过 tool_result 进入上下文,地位比 system 低。但它们仍然可能包含 prompt injection(提示词注入),也就是写在文件里、诱导模型去执行命令的文字。

所以,agent 能感知环境,不等于环境可信。

下一阶段会加权限确认。它是危险副作用发生前最后一道需要用户点头的关口,但不是唯一的防线。比如,模型读了 .env,内容就会被发给模型,这种外泄风险它拦不住。workspace 隔离、敏感路径策略和 sandbox 都不在本章范围内。

完整代码增量

下面是相对第 05 章 checkpoint(冻结的代码版本)的全部改动。没有列出的旧代码不变。

新建 src/system.ts:

import path from 'node:path'
import type { ExecutionEnv } from './env.js'

const PROJECT_INSTRUCTIONS_FILE = 'CLAUDE.md'
const MAX_PROJECT_INSTRUCTIONS_CHARS = 32_000
const MAX_GIT_STATUS_CHARS = 12_000

const BASE_INSTRUCTIONS = `You are a coding agent working in a local repository.

- Inspect relevant files before changing them.
- Prefer the provided tools over guessing about the repository.
- Treat tool output as evidence and verify the result of changes.
- Do not claim a task is complete unless the available evidence supports it.`

export type RuntimeInfo = {
  cwd: string
  platform: string
  shell: string
  localTime: string
}

export function readRuntimeInfo(): RuntimeInfo {
  return {
    cwd: process.cwd(),
    platform: process.platform,
    shell: process.env.SHELL ?? '(unknown)',
    localTime: new Date().toString(),
  }
}

function errorCode(error: unknown): string | undefined {
  if (
    error !== null &&
    typeof error === 'object' &&
    'code' in error &&
    typeof error.code === 'string'
  ) {
    return error.code
  }

  return undefined
}

function boundProjectInstructions(content: string): string {
  if (content.length <= MAX_PROJECT_INSTRUCTIONS_CHARS) {
    return content
  }

  const omitted = content.length - MAX_PROJECT_INSTRUCTIONS_CHARS

  return (
    content.slice(0, MAX_PROJECT_INSTRUCTIONS_CHARS) +
    `\n\n[Project instructions truncated: ${omitted} characters omitted]`
  )
}

function boundGitStatus(content: string): string {
  if (content.length <= MAX_GIT_STATUS_CHARS) {
    return content
  }

  const omitted = content.length - MAX_GIT_STATUS_CHARS

  return (
    content.slice(0, MAX_GIT_STATUS_CHARS) +
    `\n[Git status truncated: ${omitted} characters omitted]`
  )
}

async function readProjectInstructions(
  env: ExecutionEnv,
  cwd: string,
): Promise<string | undefined> {
  const instructionsPath = path.join(
    cwd,
    PROJECT_INSTRUCTIONS_FILE,
  )

  try {
    const content = await env.readFile(instructionsPath)
    return boundProjectInstructions(content)
  } catch (error) {
    if (errorCode(error) === 'ENOENT') {
      return undefined
    }

    throw error
  }
}

async function readGitStatus(
  env: ExecutionEnv,
  cwd: string,
): Promise<string> {
  const result = await env.execFile('git', [
    '-C',
    cwd,
    'status',
    '--short',
    '--branch',
  ])

  if (result.code !== 0) {
    return 'Not a Git repository or Git status is unavailable.'
  }

  const status = result.stdout.trim()

  return status
    ? boundGitStatus(status)
    : 'Git status is clean.'
}

export async function buildSystemPrompt(
  env: ExecutionEnv,
  runtime: RuntimeInfo = readRuntimeInfo(),
): Promise<string> {
  const [projectInstructions, gitStatus] = await Promise.all([
    readProjectInstructions(env, runtime.cwd),
    readGitStatus(env, runtime.cwd),
  ])

  const sections = [BASE_INSTRUCTIONS]

  if (projectInstructions) {
    sections.push(
      `# Project instructions (${PROJECT_INSTRUCTIONS_FILE})\n${projectInstructions}`,
    )
  } else {
    sections.push(
      `# Project instructions\nNo ${PROJECT_INSTRUCTIONS_FILE} file was found in the current working directory.`,
    )
  }

  sections.push(`# Runtime environment
Current working directory: ${runtime.cwd}
Platform: ${runtime.platform}
Shell: ${runtime.shell}
Local time: ${runtime.localTime}

Git status:
${gitStatus}`)

  return sections.join('\n\n')
}

修改 src/model.ts 中的模型边界:

export type CallModel = (
  messages: Anthropic.MessageParam[],
  tools: Anthropic.Tool[],
  system: string,
) => Promise<ModelResponse>

export const callModelAnthropic: CallModel = async (
  messages,
  tools,
  system,
) =>
  await client.messages.create({
    model: MODEL,
    max_tokens: 8192,
    system,
    messages,
    tools,
    tool_choice: {
      type: 'auto',
      disable_parallel_tool_use: false,
    },
  })

修改 src/agent.ts 的入参和调用模型的位置:

type RunAgentOptions = {
  messages: Anthropic.MessageParam[]
  system: string
  callModel: CallModel
  tools: Tool[]
  env: ExecutionEnv
}

const message = await opts.callModel(
  messages,
  definitions,
  opts.system,
)

runAgent 只使用传进来的 system 字符串,自己不读 process.cwd(),也不读项目文件。

修改 src/env.ts,把读取目录也放进现有的副作用边界:

import {
  readFile,
  readdir,
  writeFile,
} from 'node:fs/promises'

export type DirectoryEntry = {
  name: string
  type: 'file' | 'directory' | 'other'
}

export type ExecutionEnv = {
  readFile(path: string): Promise<string>
  writeFile(path: string, content: string): Promise<void>
  listFiles(path: string): Promise<DirectoryEntry[]>
  exec(command: string): Promise<CommandResult>
  execFile(
    file: string,
    args: string[],
  ): Promise<CommandResult>
}

// 加入 nodeEnv
listFiles: async (directoryPath) => {
  const entries = await readdir(directoryPath, {
    withFileTypes: true,
  })

  return entries
    .map((entry): DirectoryEntry => ({
      name: entry.name,
      type: entry.isDirectory()
        ? 'directory'
        : entry.isFile()
          ? 'file'
          : 'other',
    }))
    .sort((a, b) => a.name.localeCompare(b.name))
},

在 src/tools.ts 的 tools 数组里加入定义,并在文件里加入实现:

{
  definition: {
    name: 'list_files',
    description: 'List the direct children of one directory. This tool does not recurse into subdirectories.',
    input_schema: {
      type: 'object',
      properties: {
        path: {
          type: 'string',
          description: 'Directory path relative to the current working directory, for example "src" or ".".',
        },
      },
      required: ['path'],
    },
  },
  execute: listFilesTool,
},

const MAX_LIST_FILES_ENTRIES = 200

export async function listFilesTool(
  input: unknown,
  env: ExecutionEnv,
): Promise<string> {
  const args = asObject(input)
  const path = stringField(args, 'path')
  const entries = await env.listFiles(path)

  if (entries.length === 0) {
    return `${path}: empty directory`
  }

  const visible = entries.slice(
    0,
    MAX_LIST_FILES_ENTRIES,
  )

  const lines = visible.map((entry) =>
    entry.type === 'directory'
      ? `${entry.name}/`
      : entry.name,
  )

  const omitted = entries.length - visible.length

  if (omitted > 0) {
    lines.push(`[${omitted} more entries omitted]`)
  }

  return lines.join('\n')
}

修改 src/cli.ts:

import { buildSystemPrompt } from './system.js'

// 通过空串和 /exit 检查后,每轮重新构造
const system = await buildSystemPrompt(nodeEnv)

messages.push({
  role: 'user',
  content: line,
})

messages = await runAgent({
  messages,
  system,
  callModel: callModelAnthropic,
  tools,
  env: nodeEnv,
})

自动化测试与真实验收

新建 src/system.test.ts:

import assert from 'node:assert/strict'
import test from 'node:test'
import type {
  DirectoryEntry,
  ExecutionEnv,
} from './env.js'
import {
  buildSystemPrompt,
  type RuntimeInfo,
} from './system.js'
import { listFilesTool } from './tools.js'

const RUNTIME: RuntimeInfo = {
  cwd: '/workspace/demo',
  platform: 'darwin',
  shell: '/bin/zsh',
  localTime: 'Sun Aug 24 2026 15:30:00 GMT+0800',
}

function makeEnv(options?: {
  instructions?: string
  gitCode?: number
  gitStatus?: string
  entries?: DirectoryEntry[]
}): ExecutionEnv {
  return {
    readFile: async (path) => {
      if (
        path === '/workspace/demo/CLAUDE.md' &&
        options?.instructions !== undefined
      ) {
        return options.instructions
      }

      const error = new Error(
        `ENOENT: no such file or directory, open '${path}'`,
      ) as NodeJS.ErrnoException
      error.code = 'ENOENT'
      throw error
    },
    writeFile: async () => {},
    listFiles: async () => options?.entries ?? [],
    exec: async () => ({
      code: 0,
      stdout: '',
      stderr: '',
    }),
    execFile: async (file, args) => {
      assert.equal(file, 'git')
      assert.deepEqual(args, [
        '-C',
        '/workspace/demo',
        'status',
        '--short',
        '--branch',
      ])

      return {
        code: options?.gitCode ?? 0,
        stdout: options?.gitStatus ?? '',
        stderr: '',
      }
    },
  }
}

test('builds a layered prompt with project instructions and current Git status', async () => {
  const prompt = await buildSystemPrompt(
    makeEnv({
      instructions: 'Always run npm test before claiming completion.',
      gitStatus:
        '## codex/part2\n' +
        ' M src/agent.ts\n' +
        '?? notes.md\n',
    }),
    RUNTIME,
  )

  assert.match(prompt, /coding agent/)
  assert.match(
    prompt,
    /Always run npm test before claiming completion\./,
  )
  assert.match(prompt, /Current working directory: \/workspace\/demo/)
  assert.match(prompt, /Platform: darwin/)
  assert.match(prompt, /Shell: \/bin\/zsh/)
  assert.match(prompt, /## codex\/part2/)
  assert.match(prompt, /M src\/agent\.ts/)
  assert.ok(
    prompt.indexOf('# Project instructions') <
      prompt.indexOf('# Runtime environment'),
  )
})

test('degrades cleanly outside Git and without CLAUDE.md', async () => {
  const prompt = await buildSystemPrompt(
    makeEnv({ gitCode: 128 }),
    RUNTIME,
  )

  assert.match(prompt, /No CLAUDE\.md file was found/)
  assert.match(prompt, /Not a Git repository/)
})

test('list_files returns one bounded directory level', async () => {
  const entries: DirectoryEntry[] = Array.from(
    { length: 201 },
    (_, index) => ({
      name: `file-${String(index).padStart(3, '0')}.txt`,
      type: 'file',
    }),
  )

  entries[0] = {
    name: 'src',
    type: 'directory',
  }

  const output = await listFilesTool(
    { path: '.' },
    makeEnv({ entries }),
  )

  assert.match(output, /^src\//)
  assert.match(output, /\[1 more entries omitted\]$/)
  assert.equal(output.split('\n').length, 201)
})

现有 src/agent.test.ts 的 fake env(假环境)要加上读目录的方法,并给 runAgent 传入 system:

listFiles: async () => [],

const messages = await runAgent({
  messages: input,
  system: 'Test system prompt.',
  callModel,
  tools,
  env,
})

修改测试脚本并运行:

{
  "scripts": {
    "dev": "tsx --env-file-if-exists=.env src/cli.ts",
    "test": "tsx --test src/*.test.ts",
    "typecheck": "tsc --noEmit"
  }
}
npm test
npm run typecheck

真实验收要准备一个 fixture(测试用的样例仓库):

  1. 在它的 CLAUDE.md 里写一条看得出效果的约束;
  2. 制造一个已修改的文件和一个未跟踪的文件;
  3. 然后提问:
当前是什么分支?有哪些未提交改动?不要调用 bash。

通过的条件:

  • 分支和两个文件都答对;
  • 回答遵守了项目约束;
  • transcript(运行记录)里没有 bash 调用。

然后删掉 .git 和 CLAUDE.md,再启动一次。CLI 仍然应该能用。

章末修正:加了缓存之后,位置要重新安排

本章的“一次用户 prompt 对应一份环境快照”仍然成立。但“全部拼进 system”只适用于还没启用 prompt caching 的 checkpoint。

第 11 章真正加入缓存后:

  • system 缩成一个没有参数的常量;
  • 项目指令和运行环境改为放进消息;
  • 第一轮完整发送,之后只有变化时才追加替换块。

这次修正补上一个更准确的知识点:判断一段内容稳不稳定,不看它像“内容”还是像“环境”,而看它在所有调用方、所有会话时刻是不是逐字节不变。 coding agent 自己也可能修改 CLAUDE.md,所以项目指令同样不能留在稳定的缓存块里。