For agentic workers: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: 让 Bash runtime 维护 readFileState,修复 Bash cat file 后 Edit 仍报 File has not been read yet 的缺口,并补齐 Bash 修改已读文件后的 stale hint。
Architecture: 本次只在 agent/core 的 Bash tool runtime 层新增一个保守的 read-state producer,不改 prompt、provider-visible tool 列表、protocol、desktop、UI、remote control。bashHandler 在 foreground Bash 返回前先基于旧 read state 生成 stale hint,再按保守的读命令语义回填 Bash 读状态。
Tech Stack: TypeScript、Vitest、unbash、@zcode/contracts 的 FileSystemPort / ExecutionResult / BashOutput、现有 ReadFileStateMap。
# Using your tools 段落)。seed_read_state。packages/ui,因此无需读取 DESIGN.md。staleReadFileStateHint 已存在于 BashOutput contract。context.readFileState。pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts、pnpm --filter @zcode/core typecheck、pnpm --filter @zcode/core lint,最终按仓库约束运行 pnpm typecheck 和 pnpm lint。Purpose: 先把行为契约留在 docs,再写代码,符合仓库 NL -> Code 约束。
Files:
docs/runtime-tools/bash-read-file-state.mdChecklist:
docs/runtime-tools/bash-read-file-state.md。Bash cat/head/tail/sed -n/grep 成功且 Bash stdout 未截断后保守回填 readFileState。staleReadFileStateHint。seed_read_state。# Using your tools。BashOutput。BashOutput。Suggested doc body:
# Bash Read File State Runtime Contract
## 背景
ZCode 不依赖 `# Using your tools` 之类的 prompt 文案来要求模型先 Read,而是在 Bash runtime 内维护 read-state producer:保守识别的简单读类 Bash 命令会把文件内容写入 readFileState,使后续 Edit/Write 的 read-before-write guard 认为该文件已被读取。
## 本轮范围
- 支持 Bash `cat`、`head`、`tail`、`sed -n`、`grep`/`egrep`/`fgrep` 的保守 read-state backfill;Bash stdout 或 FileSystemPort 读文件结果被截断时不回填。
- 支持 Bash 写类命令修改已读文件后的 `staleReadFileStateHint`。
## 非范围
- 不实现 seed read state。
- 不实现 NotebookEdit。
- 不修改 prompt 或 provider-visible tool 列表。
- 不持久化 Bash 产生的 read-state metadata。
## 运行时顺序
1. Bash foreground command 运行完成。
2. runtime 先构造正常 `BashOutput`。
3. 若命令属于写类命令,扫描执行前已有的 readFileState,发现 mtime 在 Bash 开始后推进则追加 stale hint;hint 文案展示相对 cwd 的前 5 个路径,超出时追加 `and N more`,并使用 `file/files` 单复数。
4. 若命令属于保守识别的读类 Bash 命令,且 Bash stdout 未截断,runtime 重新从 FileSystemPort 读取真实文件并写入 readFileState;若 FileSystemPort 读文件结果被截断,同样跳过回填,避免把模型没看到的完整文件伪装成已读。
5. background、image output、interrupted 不产生 stale hint,也不回填 read-state。
6. 非语义失败的 provider-error 不产生 stale hint,也不回填 read-state;`grep`/`egrep`/`fgrep` 仅在 exit code 为 0 时回填。
Validation:
git diff -- docs/runtime-tools/bash-read-file-state.md
Expected: 只新增上述 spec 文档,无 runtime 代码变更。
Purpose: 先用单测锁定真实缺口和边界,避免只补 cat 一个点。
Files:
apps/zcode-cli/packages/core/tests/bash-handler.test.tsTest helper changes:
@zcode/contracts 引入 FileSystemPort、FileSystemReadTextResult、FileSystemStatResult。../src/tool/read-file-state.js 引入 createReadFileStateKey。../src/tool/types.js 引入 ReadFileStateMap 类型。[ ] 扩展 contextWith options:
fileSystemPort?: FileSystemPort;
readFileState?: ReadFileStateMap;
[ ] 在返回的 ToolExecutionContext 中透传:
fileSystemPort: options.fileSystemPort,
readFileState: options.readFileState,
[ ] 扩展 executionResult options,允许测试设置开始时间:
startedAt?: Date;
completedAt?: Date;
[ ] 将 executionResult 内的时间改成:
const now = new Date();
const startedAt = options.startedAt ?? now;
const completedAt = options.completedAt ?? startedAt;
并返回:
startedAt,
completedAt,
Add helper in test file:
function memoryFileSystemPort(
files: Record<
string,
{
content: string;
mtimeMs?: number;
revisionId?: string;
}
>,
): FileSystemPort {
return {
async stat(request) {
const file = files[request.path];
if (!file) {
throw new Error(`missing fixture file: ${request.path}`);
}
return {
path: request.path,
kind: "file",
sizeBytes: Buffer.byteLength(file.content),
mtimeMs: file.mtimeMs,
revision: {
id: file.revisionId ?? `${request.path}:${file.mtimeMs ?? 0}`,
mtimeMs: file.mtimeMs,
sizeBytes: Buffer.byteLength(file.content),
},
} satisfies FileSystemStatResult;
},
async readTextFile(request) {
const file = files[request.path];
if (!file) {
throw new Error(`missing fixture file: ${request.path}`);
}
return {
path: request.path,
content: file.content,
encoding: "utf8",
bytesRead: Buffer.byteLength(file.content),
sizeBytes: Buffer.byteLength(file.content),
truncated: false,
revision: {
id: file.revisionId ?? `${request.path}:${file.mtimeMs ?? 0}`,
mtimeMs: file.mtimeMs,
sizeBytes: Buffer.byteLength(file.content),
},
} satisfies FileSystemReadTextResult;
},
} as FileSystemPort;
}
Test cases to add under describe("bashHandler", ...):
[ ] it("backfills readFileState from successful cat before Edit", async () => { ... })
filePath = resolve(defaultCommandRoot, ".env.example")readFileState = new Map()fileSystemPort = memoryFileSystemPort({ [filePath]: { content: "FOO=bar\n", mtimeMs: 1000 } })executionPort.run returns status: "completed", exitCode: 0, stdout: "FOO=bar\n"bashHandler({ command: "cat .env.example" }, contextWith(...))readFileState.get(createReadFileStateKey(filePath, 1, undefined))?.content === "FOO=bar\n"offset === undefinedlimit === undefinedisPartialView === falsemtimeMs === 1000[ ] it("backfills ranged readFileState for head tail and sed print commands", async () => { ... })
"a\nb\nc\nd\ne\n".head -n 2 fixture.txt -> content "a\nb"、offset 1、limit 2tail -n 2 fixture.txt -> content "d\ne"、offset 4、limit 2sed -n '2,3p' fixture.txt -> content "b\nc"、offset 2、limit 2readFileState.[ ] it("backfills full readFileState for grep only when grep exits zero", async () => { ... })
0 for grep needle fixture.txt writes full file content, offset/limit undefined.1 for grep missing fixture.txt does not write read-state.[ ] it("does not backfill readFileState for complex or unsafe Bash read commands", async () => { ... })
cat fixture.txt | headcat fixture.txt > out.txtcat "$TARGET"cat fixture.txt other.txtsed -i 's/a/b/' fixture.txthead -n 0 fixture.txt[ ] it("emits stale read hint when a write-like Bash command modifies a previously read file", async () => { ... })
Prepopulate read state:
readFileState.set(createReadFileStateKey(filePath, 1, undefined), {
path: filePath,
content: "old\n",
isPartialView: false,
readAt: new Date(500),
sourceTool: "Read",
mtimeMs: 1000,
sizeBytes: 4,
});
executionResult.startedAt = new Date(1500)
fileSystemPort.stat returns mtimeMs = 2000
command: pnpm format
Assert output contains:
[This command modified 1 file you've previously read: fixture.ts. Call Read before editing.]
Assert bashToolEntry.formatModelContent?.(output) also contains the hint text.
[ ] it("does not emit stale hint when write-like Bash exits with provider error", async () => { ... })
status: "failed", exitCode: 2, command: "pnpm format" and a newer mtime.[ ] 多个已读文件变更时的 stale hint 路径格式测试
files, first 5 paths, and and 1 more.Run failing tests:
pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts
Expected before implementation: the new read-state/stale producer tests fail because Bash handler currently never writes readFileState and never fills staleReadFileStateHint.
Purpose: 新增一个小而集中的 runtime helper,承载保守的命令识别、文件读取、read-state 写入、stale hint 生成。
Files:
apps/zcode-cli/packages/core/src/tool/handlers/bash-read-file-state.tsImports:
import type { BashOutput, ExecutionResult, FileSystemPort, FileSystemStatResult, TraceContext } from "@zcode/contracts";
import { resolveWorkspacePath } from "../path-policy.js";
import {
createReadFileStateKey,
findLatestReadFileState,
normalizeReadFileStateMtimeMs,
} from "../read-file-state.js";
import type { ReadFileStateEntry, ToolExecutionContext } from "../types.js";
import { analyzeBashCommand, isBashCommandPermissionSafe, type BashCommandInvocation } from "./bash-command-parser.js";
import { isBashProviderErrorStatus } from "./bash-semantics.js";
Public interfaces:
interface BashReadFileSource {
filePath: string;
startLine?: number;
endLine?: number;
tailLines?: number;
requiresExitZero?: boolean;
}
export async function applyBashReadFileStateEffects(input: {
command: string;
context: ToolExecutionContext;
output: BashOutput;
result: ExecutionResult;
}): Promise<void>;
Core execution contract:
export async function applyBashReadFileStateEffects(input: {
command: string;
context: ToolExecutionContext;
output: BashOutput;
result: ExecutionResult;
}): Promise<void> {
const hint = await createStaleReadFileStateHint(input);
if (hint) input.output.staleReadFileStateHint = hint;
await backfillReadFileStateFromBash(input);
}
Shared guard:
shouldSkipBashReadFileStateEffects(output: BashOutput): boolean:
output.backgroundTaskId existsoutput.isImage === trueoutput.interrupted === trueRead command parser:
collectBashReadFileSources(command: string): BashReadFileSource[].|, <, >.analyzeBashCommand(command).!isBashCommandPermissionSafe(analysis).analysis.hasRedirects.parseSedPrintSource.parseCatSource.parseHeadSource.parseTailSource.analysis.commands.length === 1, try parseGrepSource./^\s*(echo|printf|true|:)\b/, ignore that segment.[].Command-specific rules:
[ ] cat
cat-n, --number-[ ] head
head10-n N--lines N--lines=N-nN-N-{ startLine: 1, endLine: count }[ ] tail
tailhead{ tailLines: count }[ ] sed
sed-n, any short flag containing n, --quiet, or --silent-i, any short flag containing i, --in-place, --in-place=*, -e, --expression/^(\d+)p$//^(\d+),(\d+)p$/[ ] grep / egrep / fgrep
grep, egrep, fgrep-/[*?[{]//^-[niwxEFGPHh]+$//^-[ABC]\d+$//^--(?:after-context|before-context|context)=\d+$/-A N, -B N, -C N where N is digits--line-number--ignore-case--word-regexp--line-regexp--extended-regexp--fixed-strings--basic-regexp--perl-regexp--with-filename--no-filename--color=never--color=autorequiresExitZero: trueBackfill algorithm:
backfillReadFileStateFromBash.shouldSkipBashReadFileStateEffects(output).!context.fileSystemPort || !context.readFileState.source.requiresExitZero ? result.exitCode === 0 : true.[ ] Resolve every source file with:
const resolvedPath = resolveWorkspacePath({
inputPath: source.filePath,
operation: "read",
workingDirectory: context.workingDirectory,
workspaceRoot: context.workspaceRoot,
});
[ ] Skip if findLatestReadFileState(context.readFileState, resolvedPath) returns an entry.
[ ] stat via context.fileSystemPort.stat({ path: resolvedPath, trace }, { signal }).
[ ] Skip if stat.kind !== "file".
[ ] Skip if stat.sizeBytes > 10 * 1024 * 1024.
[ ] Re-check context.abortSignal.aborted; skip if aborted.
[ ] readTextFile via context.fileSystemPort.readTextFile({ path: resolvedPath, maxBytes: 10 * 1024 * 1024, trace }, { signal }).
[ ] Compute selected content:
\n, start = max(1, startLine), end = max(start, endLine ?? start), skip when start > lineCount\n, pop trailing empty line, skip when no lines, count = min(tailLines, lineCount), offset = lineCount - count + 1, limit = count[ ] Set readFileState:
const entry: ReadFileStateEntry = {
path: resolvedPath,
content: selectedContent,
offset,
limit,
isPartialView: false,
readAt: new Date(),
revisionId: read.revision?.id ?? stat.revision?.id,
mtimeMs: normalizeReadFileStateMtimeMs(read.revision?.mtimeMs ?? stat.revision?.mtimeMs ?? stat.mtimeMs),
sizeBytes: read.revision?.sizeBytes ?? stat.revision?.sizeBytes ?? stat.sizeBytes,
};
context.readFileState.set(createReadFileStateKey(resolvedPath, offset ?? 1, limit), entry);
[ ] Do not set sourceTool: "Bash" in this phase. Existing type only allows "Read" | "Write" | "Edit" and compact projection treats undefined like read-compatible state; widening persistence is intentionally out of scope.
[ ] Catch and ignore per-file stat/read errors (best-effort).
Stale hint algorithm:
createStaleReadFileStateHint.shouldSkipBashReadFileStateEffects(output).!context.fileSystemPort || !context.readFileState.[ ] Return early unless command matches:
const WRITE_COMMAND_MARKERS = new RegExp(
[
"--write",
"--fix",
"--in-place",
"--auto-correct",
"\\brun\\s+format\\b",
"\\brun\\s+fix\\b",
"\\b(yarn|pnpm)\\s+format\\b",
"\\blint:file\\b",
"\\blint:fix\\b",
"\\bblack\\b",
"\\bisort\\b",
"\\bruff\\s+format\\b",
"\\bcargo\\s+(fmt|fix)\\b",
"\\brustfmt\\b",
"\\bgo\\s+fmt\\b",
"\\bterraform\\s+fmt\\b",
"\\bdprint\\s+fmt\\b",
"\\bswiftformat\\b",
"\\bphpcbf\\b",
].join("|"),
);
[ ] For each read-state entry:
entry.pathcurrentMtime = normalizeReadFileStateMtimeMs(stat.revision?.mtimeMs ?? stat.mtimeMs)entryMtime = normalizeReadFileStateMtimeMs(entry.mtimeMs)currentMtime > result.startedAt.getTime() and currentMtime > entryMtime[ ] Return undefined if no paths changed.
[ ] Return exact provider-facing string shape:
`[This command modified ${paths.length} ${paths.length === 1 ? "file" : "files"} you've previously read: ${displayPaths}${hiddenSuffix}. Call Read before editing.]`
Trace helper:
[ ] Add a local createBashReadFileStateTrace(context: ToolExecutionContext): TraceContext mirroring existing Bash/Read/Edit trace shape:
function createBashReadFileStateTrace(context: ToolExecutionContext): TraceContext {
return {
traceId: context.traceId,
spanId: context.spanId,
parentSpanId: context.parentSpanId,
sessionId: context.sessionId,
turnId: context.turnId,
} as unknown as TraceContext;
}
Run focused tests:
pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts
Expected after Phase 2 only: tests still fail until handler integration imports and calls the helper.
Purpose: 把 helper 接到 foreground Bash 完成路径,保持 output formatter 和 image/background 分支不被污染。
Files:
apps/zcode-cli/packages/core/src/tool/handlers/bash.tsapps/zcode-cli/packages/core/src/tool/handlers/bash-output.tsapps/zcode-cli/packages/contracts/src/tools/bash.tsapps/zcode-cli/packages/core/src/tool/handlers/bash-model-content.tsSteps:
[ ] Import helper:
import { applyBashReadFileStateEffects } from "./bash-read-file-state.js";
[ ] Replace current direct return at the end of bashHandler:
return toBashOutput(result, parsed, context, {
progressTiming,
stderrSuffix: cwdDecision.stderrSuffix,
});
with:
const output = await toBashOutput(result, parsed, context, {
progressTiming,
stderrSuffix: cwdDecision.stderrSuffix,
});
await applyBashReadFileStateEffects({
command: parsed.command,
context,
output,
result,
});
return output;
parsed.run_in_background branch.emptyBashOutput; backfill is tied to actual Bash execution, not empty command.Run focused tests:
pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts
Expected: new Bash read-state and stale hint tests pass.
Purpose: 防止实现只覆盖 happy path;把保守边界锁死。
Files:
apps/zcode-cli/packages/core/tests/bash-handler.test.tsapps/zcode-cli/packages/core/src/tool/handlers/bash-read-file-state.tsChecklist:
cat -n fixture.txt backfills full content.cat --number fixture.txt backfills full content.head --lines=2 fixture.txt works.head -2 fixture.txt works.tail --lines 2 fixture.txt works.sed --quiet '3p' fixture.txt works.sed --expression '3p' fixture.txt does not backfill.grep -n --color=never needle fixture.txt backfills only on exit 0.grep needle "*.txt" does not backfill.startedAt.Run focused tests:
pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts
Expected: all Bash handler tests pass.
Purpose: 确认改动没有越界,没有引入类型和 lint 问题。
Commands:
pnpm --filter @zcode/core typecheck
pnpm --filter @zcode/core lint
pnpm typecheck
pnpm lint
Checklist:
pnpm --filter @zcode/core exec vitest run tests/bash-handler.test.ts passes.pnpm --filter @zcode/core typecheck passes.pnpm --filter @zcode/core lint passes.pnpm typecheck passes.pnpm lint passes.git diff --stat only includes:
docs/runtime-tools/bash-read-file-state.mdapps/zcode-cli/packages/core/src/tool/handlers/bash-read-file-state.tsapps/zcode-cli/packages/core/src/tool/handlers/bash.tsapps/zcode-cli/packages/core/tests/bash-handler.test.tsapps/zcode-cli/packages/contracts/src/tools/bash.tspackages/ui[ ] Manually inspect provider-visible output for stale hint:
[This command modified 1 file you've previously read: fixture.ts. Call Read before editing.]
[ ] Manually inspect read-state effect for ticket path:
Bash cat .env.exampleEdit .env.exampleFile has not been read yet solely because the previous read was via Bash cat.head/tail/sed 产生的是 range view,但不是 isPartialView。这与现有 Read range 语义一致;不要把它标成 partial,否则 Edit/Write 会继续拒绝。sourceTool 或持久化 metadata。否则会牵涉 compact/resume 投影,不属于本次反馈根因。grep/egrep/fgrep 仍通过 requiresExitZero 只在 exit code 为 0 时回填。本计划完成后,ZCode 应满足:
Bash cat .env.example 能让后续 Edit .env.example 通过 read-before-write guard。Bash head/tail/sed -n/grep 的简单安全形态能按上述保守语义产生 read-state。Call Read before editing stale hint。