Open History to see the last commit
1import { FILESYSTEM_METADATA_BATCH_LIMIT } from "@t3tools/contracts";
2import {
3 isAbsolutePath,
4 isNetworkPath,
5 isWindowsAbsolutePath,
6 resolveWorkspaceFilePath,
7} from "@t3tools/shared/path";
8
9export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;
10
11export interface WorkspaceEntryCandidate {
12 readonly path: string;
13 readonly kind: "file" | "directory";
14}
15
16function basenameOfPath(path: string): string {
17 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
18 return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
19}
20
21export function needsWorkspaceBasenameLookup(relativePath: string): boolean {
22 const trimmed = relativePath.trim();
23 return (
24 trimmed !== "." &&
25 trimmed !== ".." &&
26 trimmed.length > 0 &&
27 !trimmed.includes("/") &&
28 !trimmed.includes("\\")
29 );
30}
31
32export function pickWorkspaceBasenameMatch(
33 basename: string,
34 entries: ReadonlyArray<WorkspaceEntryCandidate>,
35): string | null {
36 const target = basename.trim();
37 if (!target) return null;
38 const files = entries.filter((entry) => entry.kind === "file");
39 const exact = files.find((entry) => basenameOfPath(entry.path) === target);
40 if (exact) return exact.path;
41 const folded = target.toLowerCase();
42 const foldedMatches = files.filter(
43 (entry) => basenameOfPath(entry.path).toLowerCase() === folded,
44 );
45 return foldedMatches.length === 1 ? (foldedMatches[0]?.path ?? null) : null;
46}
47
48// Repository-relative paths can repeat the project's suffix in subfolder projects.
49function stripRepeatedWorkspacePrefix(relativePath: string, cwd: string): string | null {
50 if (isAbsolutePath(relativePath)) return null;
51 const pathSegments = relativePath.split(/[\\/]+/);
52 const cwdSegments = cwd.split(/[\\/]+/).filter(Boolean);
53 const fold = isWindowsAbsolutePath(cwd)
54 ? (segment: string | undefined) => segment?.toLowerCase()
55 : (segment: string | undefined) => segment;
56 for (let count = Math.min(cwdSegments.length, pathSegments.length - 1); count > 0; count--) {
57 const prefix = cwdSegments.slice(-count);
58 if (prefix.every((segment, index) => fold(segment) === fold(pathSegments[index]))) {
59 return pathSegments.slice(count).join("/") || null;
60 }
61 }
62 return null;
63}
64
65/**
66 * The project search query that may find a chat file link's real file, or null when the link
67 * names its file exactly. Agents often cite paths relative to a package (`cloud/http.ts`).
68 */
69export function workspaceLinkLookupQuery(relativePath: string, cwd: string): string | null {
70 const trimmed = relativePath.trim();
71 if (isAbsolutePath(trimmed) || /^(?:\.{1,2}|~)[\\/]/.test(trimmed) || /[\\/]$/.test(trimmed)) {
72 return null;
73 }
74 if (needsWorkspaceBasenameLookup(trimmed)) return trimmed;
75 return stripRepeatedWorkspacePrefix(trimmed, cwd) ?? trimmed;
76}
77
78/** The one file a chat link names: its basename, its path past a repeated prefix, or its suffix. */
79export function pickWorkspaceLinkMatch(
80 relativePath: string,
81 cwd: string,
82 entries: ReadonlyArray<WorkspaceEntryCandidate>,
83): string | null {
84 const trimmed = relativePath.trim();
85 if (needsWorkspaceBasenameLookup(trimmed)) return pickWorkspaceBasenameMatch(trimmed, entries);
86 const matches = workspaceQualifiedPathMatches(trimmed, cwd, entries);
87 return matches.length === 1 ? (matches[0] ?? null) : null;
88}
89
90function workspaceQualifiedPathMatches(
91 relativePath: string,
92 cwd: string,
93 entries: ReadonlyArray<WorkspaceEntryCandidate>,
94): ReadonlyArray<string> {
95 const stripped = stripRepeatedWorkspacePrefix(relativePath, cwd);
96 const strippedMatch =
97 stripped === null ? null : pickStrippedWorkspaceMatch(stripped, cwd, entries);
98 if (strippedMatch !== null) return [strippedMatch];
99 const suffix = relativePath.replaceAll("\\", "/");
100 return entries.flatMap((entry) => {
101 if (entry.kind !== "file") return [];
102 const path = entry.path.replaceAll("\\", "/");
103 return path === suffix || path.endsWith(`/${suffix}`) ? [entry.path] : [];
104 });
105}
106
107function pickStrippedWorkspaceMatch(
108 strippedPath: string,
109 cwd: string,
110 entries: ReadonlyArray<WorkspaceEntryCandidate>,
111): string | null {
112 const caseInsensitive = isWindowsAbsolutePath(cwd);
113 const key = (path: string) => {
114 const normalized = path.replaceAll("\\", "/");
115 return caseInsensitive ? normalized.toLowerCase() : normalized;
116 };
117 const files = entries.filter((entry) => entry.kind === "file");
118 return files.find((entry) => key(entry.path) === key(strippedPath))?.path ?? null;
119}
120
121/**
122 * The absolute path of the one file a chat link names across project roots, or null when
123 * no root has it or roots name different files. Agents cite paths relative to their repo.
124 * Nested project roots list the same file more than once, which still names one file.
125 */
126export function pickProjectLinkMatch(
127 relativePath: string,
128 searches: ReadonlyArray<{
129 readonly root: string;
130 readonly entries: ReadonlyArray<WorkspaceEntryCandidate>;
131 }>,
132): string | null {
133 const target = relativePath.trim();
134 const isBasename = needsWorkspaceBasenameLookup(target);
135 const folded = target.toLowerCase();
136 const isFoldedMatch = (entry: WorkspaceEntryCandidate) =>
137 entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded;
138 const matches = new Map<string, string>();
139 let rootHits = 0;
140 const addMatch = (path: string) => {
141 // Windows paths that differ only by case stay distinct: a directory can be case-sensitive.
142 const key = isWindowsAbsolutePath(path) ? path.replaceAll("/", "\\") : path;
143 if (!matches.has(key)) matches.set(key, path);
144 };
145 for (const { root, entries } of searches) {
146 if (isBasename) {
147 if (!entries.some(isFoldedMatch)) continue;
148 rootHits += 1;
149 const match = pickWorkspaceBasenameMatch(target, entries);
150 if (match !== null) addMatch(resolveWorkspaceFilePath(match, root));
151 } else {
152 for (const match of workspaceQualifiedPathMatches(target, root, entries)) {
153 addMatch(resolveWorkspaceFilePath(match, root));
154 }
155 }
156 }
157 if (isBasename && rootHits > 1) {
158 // A root's pick, or a root left ambiguous by case, can hide another file elsewhere.
159 for (const { root, entries } of searches) {
160 for (const entry of entries) {
161 if (isFoldedMatch(entry)) addMatch(resolveWorkspaceFilePath(entry.path, root));
162 }
163 }
164 }
165 return matches.size === 1 ? ([...matches.values()][0] ?? null) : null;
166}
167
168const AGENT_DIRECTORY_SEARCH_LIMIT = 4;
169
170/**
171 * The file a bare name cites in the latest folder the agent worked in that has one of that name.
172 * Folders are searched one at a time: the latest usually has it, and each search walks a tree.
173 */
174export async function findAgentDirectoryMatch(
175 relativePath: string,
176 directories: ReadonlyArray<string>,
177 searchRoot: (root: string) => Promise<{
178 readonly root: string;
179 readonly entries: ReadonlyArray<WorkspaceEntryCandidate>;
180 }>,
181): Promise<string | null> {
182 for (const directory of directories.slice(0, AGENT_DIRECTORY_SEARCH_LIMIT)) {
183 const { root, entries } = await searchRoot(directory);
184 const match = pickWorkspaceLinkMatch(relativePath, root, entries);
185 if (match !== null) return resolveWorkspaceFilePath(match, root);
186 }
187 return null;
188}
189
190// A quoted string or a comment is one token, so `cd` inside either is not read as a command.
191const SHELL_TOKEN = /(?<![^\s;&|()])#[^\n]*|"[^"]*"|'[^']*'|[;&|()\n]|[ \t]+|[^\s;&|()"']+/g;
192const SHELL_NAME = /(?:^|\/)(?:ba|z|da)?sh$/;
193const CD_OPTION = /^-[LPe@]*$|^--$/;
194
195/** The operands of the `cd` commands in `script`, in order, through `sh -c "<script>"`. */
196function cdOperands(script: string): Array<string> {
197 const operands: Array<string> = [];
198 let words: Array<string> = [];
199 let wordOpen = false;
200 const endCommand = () => {
201 const [name = "", ...rest] = words;
202 if (name === "cd") {
203 const operand = rest.find((word) => !CD_OPTION.test(word));
204 if (operand !== undefined) operands.push(operand);
205 } else if (SHELL_NAME.test(name)) {
206 const flag = rest.findIndex((word) => /^-[a-z]*c$/.test(word));
207 const inner = flag < 0 ? undefined : rest[flag + 1];
208 if (inner !== undefined && /^(["']).*\1$/s.test(inner)) {
209 operands.push(...cdOperands(inner.slice(1, -1)));
210 }
211 }
212 words = [];
213 wordOpen = false;
214 };
215 for (const [token] of script.matchAll(SHELL_TOKEN)) {
216 // A here-document's body is data, and where it ends is the shell's to say.
217 if (!/^["'#]/.test(token) && token.includes("<<")) break;
218 if (/^[;&|()\n]/.test(token)) endCommand();
219 else if (/^[ \t]/.test(token) || (!wordOpen && token.startsWith("#"))) wordOpen = false;
220 else if (wordOpen) words[words.length - 1] += token;
221 else {
222 words.push(token);
223 wordOpen = true;
224 }
225 }
226 endCommand();
227 return operands;
228}
229
230function literalDirectory(operand: string): string | null {
231 const path = /^["']/.test(operand) ? operand.slice(1, -1) : operand;
232 // The shell would expand these, and only it knows to what.
233 if (!isAbsolutePath(path) || /[$`*?[\]{}"']/.test(path)) return null;
234 // Search roots are local directories; the server stats each one.
235 if (isNetworkPath(path)) return null;
236 return path.includes("\\") && !isWindowsAbsolutePath(path) ? null : path;
237}
238
239interface TimelineItemSource {
240 readonly sourceThreadId: string;
241 readonly sourceItemId: string;
242}
243
244/**
245 * The folders the commands above `reply` in a thread's timeline changed into, the latest first.
246 * A reply cites paths relative to where the agent worked, which no project has to be rooted at.
247 * Rows below the reply, a fork's own commands under an inherited one included, came after it.
248 */
249export function agentWorkingDirectories(
250 items: ReadonlyArray<
251 TimelineItemSource & { readonly item: { readonly type: string; readonly input?: unknown } }
252 >,
253 reply: TimelineItemSource,
254): ReadonlyArray<string> {
255 const directories = new Set<string>();
256 const replyIndex = items.findIndex(
257 (row) => row.sourceThreadId === reply.sourceThreadId && row.sourceItemId === reply.sourceItemId,
258 );
259 for (let index = replyIndex - 1; index >= 0; index--) {
260 const item = items[index]?.item;
261 if (item?.type !== "command_execution" || typeof item.input !== "string") continue;
262 for (const operand of cdOperands(item.input).reverse()) {
263 const directory = literalDirectory(operand);
264 if (directory !== null) directories.add(directory);
265 if (directories.size === FILESYSTEM_METADATA_BATCH_LIMIT) return [...directories];
266 }
267 }
268 return [...directories];
269}