Skip to content

Commit a2b3cc1

Browse files
feat(opencode): add changed-files tree with change indicators (anomalyco#815)
* feat(opencode): add changed-files tree with change indicators * feat(opencode): address changed-files review feedback --------- Co-authored-by: Affaan Mustafa <[email protected]>
1 parent 0f40fd0 commit a2b3cc1

7 files changed

Lines changed: 417 additions & 6 deletions

File tree

‎.opencode/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export const metadata = {
7474
"format-code",
7575
"lint-check",
7676
"git-summary",
77+
"changed-files",
7778
],
7879
},
7980
}

‎.opencode/opencode.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@
3131
"write": true,
3232
"edit": true,
3333
"bash": true,
34-
"read": true
34+
"read": true,
35+
"changed-files": true
3536
}
3637
},
3738
"planner": {

‎.opencode/plugins/ecc-hooks.ts‎

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@
1414
*/
1515

1616
import type { PluginInput } from "@opencode-ai/plugin"
17+
import * as fs from "fs"
18+
import * as path from "path"
19+
import {
20+
initStore,
21+
recordChange,
22+
clearChanges,
23+
} from "./lib/changed-files-store.js"
24+
import changedFilesTool from "../tools/changed-files.js"
1725

1826
export const ECCHooksPlugin = async ({
1927
client,
@@ -23,9 +31,25 @@ export const ECCHooksPlugin = async ({
2331
}: PluginInput) => {
2432
type HookProfile = "minimal" | "standard" | "strict"
2533

26-
// Track files edited in current session for console.log audit
34+
const worktreePath = worktree || directory
35+
initStore(worktreePath)
36+
2737
const editedFiles = new Set<string>()
2838

39+
function resolvePath(p: string): string {
40+
if (path.isAbsolute(p)) return p
41+
return path.join(worktreePath, p)
42+
}
43+
44+
const pendingToolChanges = new Map<string, { path: string; type: "added" | "modified" }>()
45+
let writeCounter = 0
46+
47+
function getFilePath(args: Record<string, unknown> | undefined): string | null {
48+
if (!args) return null
49+
const p = (args.filePath ?? args.file_path ?? args.path) as string | undefined
50+
return typeof p === "string" && p.trim() ? p : null
51+
}
52+
2953
// Helper to call the SDK's log API with correct signature
3054
const log = (level: "debug" | "info" | "warn" | "error", message: string) =>
3155
client.app.log({ body: { service: "ecc", level, message } })
@@ -73,8 +97,8 @@ export const ECCHooksPlugin = async ({
7397
* Action: Runs prettier --write on the file
7498
*/
7599
"file.edited": async (event: { path: string }) => {
76-
// Track edited files for console.log audit
77100
editedFiles.add(event.path)
101+
recordChange(event.path, "modified")
78102

79103
// Auto-format JS/TS files
80104
if (hookEnabled("post:edit:format", ["strict"]) && event.path.match(/\.(ts|tsx|js|jsx)$/)) {
@@ -111,9 +135,24 @@ export const ECCHooksPlugin = async ({
111135
* Action: Runs tsc --noEmit to check for type errors
112136
*/
113137
"tool.execute.after": async (
114-
input: { tool: string; args?: { filePath?: string } },
138+
input: { tool: string; callID?: string; args?: { filePath?: string; file_path?: string; path?: string } },
115139
output: unknown
116140
) => {
141+
const filePath = getFilePath(input.args as Record<string, unknown>)
142+
if (input.tool === "edit" && filePath) {
143+
recordChange(filePath, "modified")
144+
}
145+
if (input.tool === "write" && filePath) {
146+
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
147+
const pending = pendingToolChanges.get(key)
148+
if (pending) {
149+
recordChange(pending.path, pending.type)
150+
pendingToolChanges.delete(key)
151+
} else {
152+
recordChange(filePath, "modified")
153+
}
154+
}
155+
117156
// Check if a TypeScript file was edited
118157
if (
119158
hookEnabled("post:edit:typecheck", ["strict"]) &&
@@ -152,8 +191,25 @@ export const ECCHooksPlugin = async ({
152191
* Action: Warns about potential security issues
153192
*/
154193
"tool.execute.before": async (
155-
input: { tool: string; args?: Record<string, unknown> }
194+
input: { tool: string; callID?: string; args?: Record<string, unknown> }
156195
) => {
196+
if (input.tool === "write") {
197+
const filePath = getFilePath(input.args)
198+
if (filePath) {
199+
const absPath = resolvePath(filePath)
200+
let type: "added" | "modified" = "modified"
201+
try {
202+
if (typeof fs.existsSync === "function") {
203+
type = fs.existsSync(absPath) ? "modified" : "added"
204+
}
205+
} catch {
206+
type = "modified"
207+
}
208+
const key = input.callID ?? `write-${++writeCounter}-${filePath}`
209+
pendingToolChanges.set(key, { path: filePath, type })
210+
}
211+
}
212+
157213
// Git push review reminder
158214
if (
159215
hookEnabled("pre:bash:git-push-reminder", "strict") &&
@@ -293,6 +349,8 @@ export const ECCHooksPlugin = async ({
293349
if (!hookEnabled("session:end-marker", ["minimal", "standard", "strict"])) return
294350
log("info", "[ECC] Session ended - cleaning up")
295351
editedFiles.clear()
352+
clearChanges()
353+
pendingToolChanges.clear()
296354
},
297355

298356
/**
@@ -303,6 +361,10 @@ export const ECCHooksPlugin = async ({
303361
* Action: Updates tracking
304362
*/
305363
"file.watcher.updated": async (event: { path: string; type: string }) => {
364+
let changeType: "added" | "modified" | "deleted" = "modified"
365+
if (event.type === "create" || event.type === "add") changeType = "added"
366+
else if (event.type === "delete" || event.type === "remove") changeType = "deleted"
367+
recordChange(event.path, changeType)
306368
if (event.type === "change" && event.path.match(/\.(ts|tsx|js|jsx)$/)) {
307369
editedFiles.add(event.path)
308370
}
@@ -394,7 +456,7 @@ export const ECCHooksPlugin = async ({
394456
"",
395457
"## Active Plugin: Everything Claude Code v1.8.0",
396458
"- Hooks: file.edited, tool.execute.before/after, session.created/idle/deleted, shell.env, compacting, permission.ask",
397-
"- Tools: run-tests, check-coverage, security-audit, format-code, lint-check, git-summary",
459+
"- Tools: run-tests, check-coverage, security-audit, format-code, lint-check, git-summary, changed-files",
398460
"- Agents: 13 specialized (planner, architect, tdd-guide, code-reviewer, security-reviewer, build-error-resolver, e2e-runner, refactor-cleaner, doc-updater, go-reviewer, go-build-resolver, database-reviewer, python-reviewer)",
399461
"",
400462
"## Key Principles",
@@ -449,6 +511,10 @@ export const ECCHooksPlugin = async ({
449511
// Everything else: let user decide
450512
return { approved: undefined }
451513
},
514+
515+
tool: {
516+
"changed-files": changedFilesTool,
517+
},
452518
}
453519
}
454520

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import * as path from "path"
2+
3+
export type ChangeType = "added" | "modified" | "deleted"
4+
5+
const changes = new Map<string, ChangeType>()
6+
let worktreeRoot = ""
7+
8+
export function initStore(worktree: string): void {
9+
worktreeRoot = worktree || process.cwd()
10+
}
11+
12+
function toRelative(p: string): string {
13+
if (!p) return ""
14+
const normalized = path.normalize(p)
15+
if (path.isAbsolute(normalized) && worktreeRoot) {
16+
const rel = path.relative(worktreeRoot, normalized)
17+
return rel.startsWith("..") ? normalized : rel
18+
}
19+
return normalized
20+
}
21+
22+
export function recordChange(filePath: string, type: ChangeType): void {
23+
const rel = toRelative(filePath)
24+
if (!rel) return
25+
changes.set(rel, type)
26+
}
27+
28+
export function getChanges(): Map<string, ChangeType> {
29+
return new Map(changes)
30+
}
31+
32+
export function clearChanges(): void {
33+
changes.clear()
34+
}
35+
36+
export type TreeNode = {
37+
name: string
38+
path: string
39+
changeType?: ChangeType
40+
children: TreeNode[]
41+
}
42+
43+
function addToTree(children: TreeNode[], segs: string[], fullPath: string, changeType: ChangeType): void {
44+
if (segs.length === 0) return
45+
const [head, ...rest] = segs
46+
let child = children.find((c) => c.name === head)
47+
48+
if (rest.length === 0) {
49+
if (child) {
50+
child.changeType = changeType
51+
child.path = fullPath
52+
} else {
53+
children.push({ name: head, path: fullPath, changeType, children: [] })
54+
}
55+
return
56+
}
57+
58+
if (!child) {
59+
const dirPath = segs.slice(0, -rest.length).join(path.sep)
60+
child = { name: head, path: dirPath, children: [] }
61+
children.push(child)
62+
}
63+
addToTree(child.children, rest, fullPath, changeType)
64+
}
65+
66+
export function buildTree(filter?: ChangeType): TreeNode[] {
67+
const root: TreeNode[] = []
68+
for (const [relPath, changeType] of changes) {
69+
if (filter && changeType !== filter) continue
70+
const segs = relPath.split(path.sep).filter(Boolean)
71+
if (segs.length === 0) continue
72+
addToTree(root, segs, relPath, changeType)
73+
}
74+
75+
function sortNodes(nodes: TreeNode[]): TreeNode[] {
76+
return [...nodes].sort((a, b) => {
77+
const aIsFile = a.changeType !== undefined
78+
const bIsFile = b.changeType !== undefined
79+
if (aIsFile !== bIsFile) return aIsFile ? 1 : -1
80+
return a.name.localeCompare(b.name)
81+
}).map((n) => ({ ...n, children: sortNodes(n.children) }))
82+
}
83+
return sortNodes(root)
84+
}
85+
86+
export function getChangedPaths(filter?: ChangeType): Array<{ path: string; changeType: ChangeType }> {
87+
const list: Array<{ path: string; changeType: ChangeType }> = []
88+
for (const [p, t] of changes) {
89+
if (filter && t !== filter) continue
90+
list.push({ path: p, changeType: t })
91+
}
92+
list.sort((a, b) => a.path.localeCompare(b.path))
93+
return list
94+
}
95+
96+
export function hasChanges(): boolean {
97+
return changes.size > 0
98+
}

‎.opencode/tools/changed-files.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { tool } from "@opencode-ai/plugin/tool"
2+
import {
3+
buildTree,
4+
getChangedPaths,
5+
hasChanges,
6+
type ChangeType,
7+
type TreeNode,
8+
} from "../plugins/lib/changed-files-store.js"
9+
10+
const INDICATORS: Record<ChangeType, string> = {
11+
added: "+",
12+
modified: "~",
13+
deleted: "-",
14+
}
15+
16+
function renderTree(nodes: TreeNode[], indent: string): string {
17+
const lines: string[] = []
18+
for (const node of nodes) {
19+
const indicator = node.changeType ? ` (${INDICATORS[node.changeType]})` : ""
20+
const name = node.changeType ? `${node.name}${indicator}` : `${node.name}/`
21+
lines.push(`${indent}${name}`)
22+
if (node.children.length > 0) {
23+
lines.push(renderTree(node.children, `${indent} `))
24+
}
25+
}
26+
return lines.join("\n")
27+
}
28+
29+
export default tool({
30+
description:
31+
"List files changed by agents in this session as a navigable tree. Shows added (+), modified (~), and deleted (-) indicators. Use filter to show only specific change types. Returns paths for git diff.",
32+
args: {
33+
filter: tool.schema
34+
.enum(["all", "added", "modified", "deleted"])
35+
.optional()
36+
.describe("Filter by change type (default: all)"),
37+
format: tool.schema
38+
.enum(["tree", "json"])
39+
.optional()
40+
.describe("Output format: tree for terminal display, json for structured data (default: tree)"),
41+
},
42+
async execute(args, context) {
43+
const filter = args.filter === "all" || !args.filter ? undefined : (args.filter as ChangeType)
44+
const format = args.format ?? "tree"
45+
46+
if (!hasChanges()) {
47+
return JSON.stringify({ changed: false, message: "No files changed in this session" })
48+
}
49+
50+
const paths = getChangedPaths(filter)
51+
52+
if (format === "json") {
53+
return JSON.stringify(
54+
{
55+
changed: true,
56+
filter: filter ?? "all",
57+
files: paths.map((p) => ({ path: p.path, changeType: p.changeType })),
58+
diffCommands: paths
59+
.filter((p) => p.changeType !== "added")
60+
.map((p) => `git diff ${p.path}`),
61+
},
62+
null,
63+
2
64+
)
65+
}
66+
67+
const tree = buildTree(filter)
68+
const treeStr = renderTree(tree, "")
69+
const diffHint = paths
70+
.filter((p) => p.changeType !== "added")
71+
.slice(0, 5)
72+
.map((p) => ` git diff ${p.path}`)
73+
.join("\n")
74+
75+
let output = `Changed files (${paths.length}):\n\n${treeStr}`
76+
if (diffHint) {
77+
output += `\n\nTo view diff for a file:\n${diffHint}`
78+
}
79+
return output
80+
},
81+
})

‎.opencode/tools/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ export { default as securityAudit } from "./security-audit.js"
1111
export { default as formatCode } from "./format-code.js"
1212
export { default as lintCheck } from "./lint-check.js"
1313
export { default as gitSummary } from "./git-summary.js"
14+
export { default as changedFiles } from "./changed-files.js"

0 commit comments

Comments
 (0)