Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
fix(windows): read paths the Windows way in hooks, check and skill anchors
Shrish Dwivedi031727dd45d2
diff --git a/src/claude/note-signals.ts b/src/claude/note-signals.tsindex c0813b98..94463d06 100644--- a/src/claude/note-signals.ts+++ b/src/claude/note-signals.ts@@ -63,8 +63,16 @@ const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit']);*/const BASH_WRITE =/\bsed\s+(?:-[a-zA-Z]+\s+)*-i|\bperl\s+-[a-z]*i|\btee\s|(?:^|[^>&0-9])>>?\s*[\w./~-]+\.\w+|\bgit\s+apply\b|\bapply_patch\b|\bopen\([^)]*,\s*['"][wa]|\.write_text\(|\bwriteFileSync\(/m;-/** File names in a command, by their extension. */-const FILE_WORD = /[\w./-]+\.(?:go|tsx?|jsx?|mjs|cjs|py|rb|rs|java|kt|swift|cs|php|c|h|cc|cpp|hpp|scala|sql|ya?ml|json|toml|sh|css|scss|vue|svelte)\b/g;+const CODE_EXT = '(?:go|tsx?|jsx?|mjs|cjs|py|rb|rs|java|kt|swift|cs|php|c|h|cc|cpp|hpp|scala|sql|ya?ml|json|toml|sh|css|scss|vue|svelte)';+/**+ * File names in a command, by their extension. On Windows a path also has a drive and backslashes+ * (`C:\Users\me\shop\src\client.ts`, or `C:/Users/...` in Git Bash): without them only `client.ts`, or a+ * path on the wrong drive, would be read.+ */+export function fileWordRe(platform: NodeJS.Platform = process.platform): RegExp {+ return platform === 'win32' ? new RegExp(`(?:\\b[A-Za-z]:)?[\\w./\\\\~-]+\\.${CODE_EXT}\\b`, 'g') : new RegExp(`[\\w./-]+\\.${CODE_EXT}\\b`, 'g');+}+const FILE_WORD = fileWordRe();/** `cd <dir> &&` at the start of a command: where its relative paths start. */const LEADING_CD = /^\s*cd\s+(["']?)([^"'&;|]+?)\1\s*(?:&&|;)/;diff --git a/src/cli.ts b/src/cli.tsindex c691d879..8eeaa44c 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -72,7 +72,7 @@ import { addRepo, clearCloud, cloudEnabled, fetchMe, fetchTeam, isError, readCloimport { inWorkspace, maybeSyncInBackground, recordActivity, runSyncChild, syncRepo, workspaceLearnings } from "./cloud/workspace-sync.js";import type { CheckResult } from "./check/types.js";import { checkLocally } from "./check/local-check.js";-import { findLearning, liveLearnings } from "./notes/learning-fields.js";+import { findLearning, learningFileName, liveLearnings } from "./notes/learning-fields.js";import { savedIdLine } from "./notes/replace.js";import { formatOverlap, maybeRefreshBranches, overlapsWith, pushedWhen, readBranchCache, refreshBranches } from "./notes/branches.js";import { ensureRepoTrail, LEARNINGS_DIR } from "./notes/repo-trail.js";@@ -2156,7 +2156,7 @@ async function runTeamCheck(dir: string, opts: { base?: string; json?: boolean }asker: me,session: sessionKey(repo) ?? `${me}-${new Date().toISOString().slice(0, 10)}`,file_count: files.length,- shown_paths: [...new Set(sources.map((s) => s.path!.slice(s.path!.lastIndexOf("/") + 1)))],+ shown_paths: [...new Set(sources.map((s) => learningFileName(s.path!)))],shown_authors: [...new Set(sources.map((s) => s.author ?? ""))],at: new Date().toISOString(),});diff --git a/src/init/plain-file.ts b/src/init/plain-file.tsindex f369dc73..f7664e2e 100644--- a/src/init/plain-file.ts+++ b/src/init/plain-file.ts@@ -17,6 +17,8 @@ import { basename, dirname, join } from 'node:path';/** A read-only descriptor of a plain file, or a throw. `follow`: a link to a plain file is allowed. */export function openPlain(path: string, opts: { follow?: boolean } = {}): number {const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (opts.follow ? 0 : constants.O_NOFOLLOW ?? 0);+ // Windows has no O_NOFOLLOW, and open follows a link there: refuse one seen before the open.+ if (!opts.follow && constants.O_NOFOLLOW === undefined && lstatSync(path).isSymbolicLink()) throw new Error('a link');const fd = openSync(path, flags);try {if (!fstatSync(fd).isFile()) throw new Error('not a plain file');diff --git a/src/skills/anchors-cli.ts b/src/skills/anchors-cli.tsindex eb3bc385..4c144438 100644--- a/src/skills/anchors-cli.ts+++ b/src/skills/anchors-cli.ts@@ -12,7 +12,7 @@*/import { createHash } from 'node:crypto';import { lstatSync, readdirSync, statSync } from 'node:fs';-import { dirname, join, normalize, relative, resolve, sep } from 'node:path';+import { dirname, join, posix, relative, resolve, sep } from 'node:path';import { exists, readSmall } from './anchors-git.js';import { readPlain } from '../init/plain-file.js';import { trailPath, writePrivate } from '../util/private-fs.js';@@ -35,6 +35,12 @@ export interface Cli { prog: string; pkgDir: string; target: string }const inside = (top: string, p: string) => p === top || p.startsWith(top + sep);const isDir = (p: string) => { try { return statSync(p).isDirectory(); } catch { return false; } };+/**+ * A bin target or a `node <file>` word as one form: forward slashes, normalized, no `./`. `dist/cli.js` on every+ * platform, as package.json and the shell write it; `path.normalize` would make it `dist\cli.js` on Windows.+ */+export const binTarget = (p: string): string => posix.normalize(p.replace(/\\/g, '/')).replace(/^\.\//, '');+/** The bins of the nearest package.json from the step's folder up to the checkout: name to target. null when none or unreadable. */export function binsNear(checkout: string, dir: string): { pkgDir: string; bins: Map<string, string> } | null {const top = resolve(checkout);@@ -50,7 +56,7 @@ export function binsNear(checkout: string, dir: string): { pkgDir: string; bins:else if (pkg?.bin && typeof pkg.bin === 'object') {for (const [k, v] of Object.entries(pkg.bin as Record<string, unknown>)) if (typeof v === 'string') bins.set(k, v);}- for (const [k, v] of bins) bins.set(k, normalize(v).replace(/^\.\//, ''));+ for (const [k, v] of bins) bins.set(k, binTarget(v));return bins.size ? { pkgDir: d, bins } : null;}if (d === top) return null;diff --git a/src/skills/anchors-wide.ts b/src/skills/anchors-wide.tsindex 59a298ca..6d964580 100644--- a/src/skills/anchors-wide.ts+++ b/src/skills/anchors-wide.ts@@ -17,7 +17,7 @@ import { lstatSync, readdirSync, statSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { ParsedSkill } from './types.js';import { gitOf, readSmall, refOid } from './anchors-git.js';-import { binsNear, cliNames, subcommandGone, type Cli } from './anchors-cli.js';+import { binTarget, binsNear, cliNames, subcommandGone, type Cli } from './anchors-cli.js';import { leadingCds, simpleCommands } from '../trace/shell.js';import { programWords } from '../trace/shell-words.js';import { unquote } from '../trace/shell-scan.js';@@ -192,7 +192,7 @@ function cliCall(w: string[], bins: Map<string, string>): { prog: string; x: str} else if (w[0] === 'node') {const t = w[1];if (!t || t.startsWith('-')) return null;- const n = t.replace(/^\.\//, '');+ const n = binTarget(t);prog = [...bins].find(([, target]) => target === n)?.[0];i = 2;}diff --git a/src/skills/update-gate.ts b/src/skills/update-gate.tsindex 836f9c4f..7803c900 100644--- a/src/skills/update-gate.ts+++ b/src/skills/update-gate.ts@@ -247,7 +247,8 @@ function updateInTranscript(r: UpdateReceipt, name: string, offerId: string, calfunction shown(p: string, env: NodeJS.ProcessEnv): string {const home = env.HOME || homedir();const rel = home && isAbsolute(p) ? relative(home, p) : '';- return rel && !rel.startsWith('..') && !isAbsolute(rel) ? `~/${rel.split(sep).join('/')}` : p;+ // Forward slashes either way: the person pastes it into Git Bash or PowerShell on Windows, and both take them.+ return rel && !rel.startsWith('..') && !isAbsolute(rel) ? `~/${rel.split(sep).join('/')}` : p.split(sep).join('/');}/** What changed, in words: `step 4 is now '…'`, `step 5 added: '…'`, `the 4 steps that just worked replace the old ones`. */diff --git a/test/skills-anchors-wide.test.ts b/test/skills-anchors-wide.test.tsindex b783ce9b..28baccf2 100644--- a/test/skills-anchors-wide.test.ts+++ b/test/skills-anchors-wide.test.ts@@ -15,6 +15,7 @@ import { join } from "node:path";import { tmpRepo } from "./helpers.js";import { cloneShape } from "./anchors-clone-fixture.js";import { WIDE_SCAN_MS, wideAnchorsOf, wideGone, type WideAnchor } from "../src/skills/anchors-wide.js";+import { binTarget } from "../src/skills/anchors-cli.js";import { goneAnchors } from "../src/skills/anchors.js";import type { ParsedSkill } from "../src/skills/types.js";import { timeBar } from "./machine-speed.js";@@ -202,6 +203,10 @@ function cliBox(tag: string, src = CLI_SRC): Box {return b;}+test("a bin target and a node <file> word are one form on every platform: dist/cli.js, never dist\\cli.js", () => {+ for (const t of ["dist/cli.js", "./dist/cli.js", "dist\\cli.js", ".\\dist\\cli.js", "dist//cli.js"]) assert.equal(binTarget(t), "dist/cli.js", t);+});+test("subcommand: the fixture CLI with connect removed (the b92c22e shape) is gone; with it, not", () => {const b = cliBox("sub");const forms = ["acme connect", "npx acme connect --token-file x", "npm exec acme connect", "node dist/cli.js connect", "node ./dist/cli.js connect"];diff --git a/test/trail-note-ask.test.ts b/test/trail-note-ask.test.tsindex ae9ae6bb..68005c1d 100644--- a/test/trail-note-ask.test.ts+++ b/test/trail-note-ask.test.ts@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { BRAND_ENV } from '../src/brand.js';import { main } from '../src/claude/hooks.js';-import { noteAsk, noteSignals } from '../src/claude/note-signals.js';+import { fileWordRe, noteAsk, noteSignals } from '../src/claude/note-signals.js';import { ensureRepoHome } from '../src/notes/home.js';let n = 0;@@ -173,3 +173,10 @@ test('the Stop hook asks once per sign, three times a session at most, and neverassert.equal(await stop({ session_id: 's1', transcript_path: t }), '', 'three asks a session at most');assert.notEqual(await stop({ session_id: 's2', transcript_path: t }), '', 'a new session is asked again');});++test("a shell edit's file is read whole on Windows too: the drive, backslashes, Git Bash's slashes, a short name", () => {+ const cmd = "sed -i '' 's/4/6/' C:\\Users\\priya\\shop\\src\\client.ts && cat C:/Users/priya/shop/go.mod D:\\RUNNER~1\\shop\\main.go";+ assert.deepEqual(cmd.match(fileWordRe('win32')), ['C:\\Users\\priya\\shop\\src\\client.ts', 'D:\\RUNNER~1\\shop\\main.go']);+ assert.deepEqual("sed -i 's/4/6/' /work/app/src/client.ts".match(fileWordRe('linux')), ['/work/app/src/client.ts']);+ assert.deepEqual("sed -i 's/4/6/' C:/work/app/src/client.ts".match(fileWordRe('win32')), ['C:/work/app/src/client.ts']);+});