claude-dev-env 8.109.3 → 8.109.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,12 @@
1
1
  /**
2
- * Publish a Claude Code lookup path as a directory pointer to the agents home.
2
+ * Publish Claude Code lookup paths that point into the agents home.
3
3
  *
4
- * Skills and agents live under the agents home. Claude Code still discovers
5
- * them at `managedRoot/skills` and `managedRoot/agents`, so the installer
6
- * writes those two paths as directory pointers (a POSIX symlink, or a Windows
7
- * junction). One helper owns the create, refresh, and relocate steps.
4
+ * Agents, hooks, and scripts live under the agents home. Claude Code discovers
5
+ * them at `managedRoot/<name>`, so the installer writes those paths as
6
+ * directory pointers (a POSIX symlink, or a Windows junction). The skills
7
+ * lookup is a folder of pointers, one per shipped skill, so Claude reads
8
+ * the shared skills while the agents home keeps the skill files and the plugin
9
+ * links. One helper owns the create, refresh, and relocate steps.
8
10
  */
9
11
 
10
12
  import {
@@ -18,7 +20,7 @@ import {
18
20
  symlinkSync,
19
21
  unlinkSync,
20
22
  } from 'node:fs';
21
- import { dirname, join, resolve } from 'node:path';
23
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
22
24
  import { normalizePathForComparison } from './resolve-install-root.mjs';
23
25
 
24
26
  export const DIRECTORY_POINTER_TYPE_JUNCTION = 'junction';
@@ -59,6 +61,17 @@ export function isDirectoryPointerTo(pointerPath, targetPath) {
59
61
  === normalizePathForComparison(resolve(targetPath));
60
62
  }
61
63
 
64
+ /**
65
+ * Report whether linkPath is a symbolic link that does not aim at targetPath.
66
+ *
67
+ * @param {string} linkPath
68
+ * @param {string} targetPath
69
+ * @returns {boolean}
70
+ */
71
+ export function isLinkToOtherDirectory(linkPath, targetPath) {
72
+ return readPathKind(linkPath) === 'symlink' && !isDirectoryPointerTo(linkPath, targetPath);
73
+ }
74
+
62
75
  /**
63
76
  * Make pointerPath a directory pointer to targetPath.
64
77
  *
@@ -106,6 +119,62 @@ export function ensureDirectoryPointer(pointerPath, targetPath, options = {}) {
106
119
  };
107
120
  }
108
121
 
122
+ /**
123
+ * Make lookupDirectory a folder with one directory pointer per directory in
124
+ * installDirectory.
125
+ *
126
+ * A link at lookupDirectory, whether it aims at installDirectory or somewhere
127
+ * else, is unlinked and the folder takes its place. The directory it aimed at
128
+ * is left alone. A per-skill link that aims at another directory is left in
129
+ * place. A link whose target under
130
+ * installDirectory is gone is removed. A symbolic link inside installDirectory
131
+ * is not linked here, which keeps plugin links out of this folder and leaves a
132
+ * skill a user linked there without an entry. A
133
+ * directory in lookupDirectory that installDirectory lacks is a personal skill
134
+ * and stays where it is. A file in a same-named lookup directory that
135
+ * installDirectory already holds moves to conflictBackupDirectory before the
136
+ * merge, so a local edit survives.
137
+ *
138
+ * @param {string} lookupDirectory Claude lookup path (for example `~/.claude/skills`).
139
+ * @param {string} installDirectory Canonical skills folder (for example `~/.agents/skills`).
140
+ * @param {string} conflictBackupDirectory Folder that receives displaced lookup files.
141
+ * @returns {{ createdLinkPaths: string[], linkPaths: string[] }} The links this
142
+ * call created, and every link to a directory in installDirectory after the call.
143
+ */
144
+ export function ensureLinkedSkillFolder(lookupDirectory, installDirectory, conflictBackupDirectory) {
145
+ const resolvedLookup = resolve(lookupDirectory);
146
+ const resolvedInstall = resolve(installDirectory);
147
+ mkdirSync(resolvedInstall, { recursive: true });
148
+
149
+ const lookupKind = readPathKind(resolvedLookup);
150
+ if (lookupKind === 'symlink') {
151
+ unlinkSync(resolvedLookup);
152
+ console.log(` Replaced the link at ${resolvedLookup} with a folder of skill links`);
153
+ } else if (lookupKind === 'file') {
154
+ throw new Error(`Cannot publish linked skills: ${resolvedLookup} is a file`);
155
+ }
156
+ mkdirSync(resolvedLookup, { recursive: true });
157
+
158
+ removeDanglingLinksInto(resolvedLookup, resolvedInstall);
159
+ const createdLinkPaths = [];
160
+ const linkPaths = [];
161
+ for (const eachEntry of readdirSync(resolvedInstall, { withFileTypes: true })) {
162
+ if (!eachEntry.isDirectory()) continue;
163
+ const linkPath = join(resolvedLookup, eachEntry.name);
164
+ const targetPath = join(resolvedInstall, eachEntry.name);
165
+ if (isLinkToOtherDirectory(linkPath, targetPath)) continue;
166
+ if (readPathKind(linkPath) === 'directory') {
167
+ setAsideConflictingEntries(linkPath, targetPath, join(conflictBackupDirectory, eachEntry.name));
168
+ }
169
+ const publication = ensureDirectoryPointer(linkPath, targetPath);
170
+ linkPaths.push(linkPath);
171
+ if (publication.action === POINTER_ACTION_CREATED) {
172
+ createdLinkPaths.push(linkPath);
173
+ }
174
+ }
175
+ return { createdLinkPaths, linkPaths };
176
+ }
177
+
109
178
  /**
110
179
  * Remove a directory pointer when it aims at the expected target.
111
180
  *
@@ -125,7 +194,7 @@ export function unlinkDirectoryPointerIfMatch(pointerPath, targetPath) {
125
194
  * @param {string} absolutePath
126
195
  * @returns {'missing' | 'symlink' | 'directory' | 'file' | 'other'}
127
196
  */
128
- function readPathKind(absolutePath) {
197
+ export function readPathKind(absolutePath) {
129
198
  let stats;
130
199
  try {
131
200
  stats = lstatSync(absolutePath);
@@ -147,6 +216,55 @@ function readPathKind(absolutePath) {
147
216
  return 'other';
148
217
  }
149
218
 
219
+ /**
220
+ * Remove links in lookupDirectory whose target sits under installDirectory and
221
+ * no longer exists.
222
+ *
223
+ * @param {string} lookupDirectory
224
+ * @param {string} installDirectory
225
+ * @returns {void}
226
+ */
227
+ function removeDanglingLinksInto(lookupDirectory, installDirectory) {
228
+ for (const eachEntry of readdirSync(lookupDirectory, { withFileTypes: true })) {
229
+ if (!eachEntry.isSymbolicLink()) continue;
230
+ const linkPath = join(lookupDirectory, eachEntry.name);
231
+ const linkTarget = resolve(lookupDirectory, readlinkSync(linkPath));
232
+ const targetOffset = relative(installDirectory, linkTarget);
233
+ const targetIsInside = targetOffset !== ''
234
+ && !isAbsolute(targetOffset)
235
+ && targetOffset.split(sep)[0] !== '..';
236
+ if (targetIsInside && !existsSync(linkPath)) {
237
+ unlinkSync(linkPath);
238
+ }
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Move each entry in sourceDirectory that destinationDirectory already holds
244
+ * into backupDirectory, keeping its relative path. A directory that exists on
245
+ * both sides is walked the same way. Entries the destination lacks stay in
246
+ * place for the merge that follows.
247
+ *
248
+ * @param {string} sourceDirectory
249
+ * @param {string} destinationDirectory
250
+ * @param {string} backupDirectory
251
+ * @returns {void}
252
+ */
253
+ function setAsideConflictingEntries(sourceDirectory, destinationDirectory, backupDirectory) {
254
+ for (const eachEntry of readdirSync(sourceDirectory, { withFileTypes: true })) {
255
+ const sourceChild = join(sourceDirectory, eachEntry.name);
256
+ const destinationChild = join(destinationDirectory, eachEntry.name);
257
+ if (!existsSync(destinationChild)) continue;
258
+ if (eachEntry.isDirectory() && readPathKind(destinationChild) === 'directory') {
259
+ setAsideConflictingEntries(sourceChild, destinationChild, join(backupDirectory, eachEntry.name));
260
+ continue;
261
+ }
262
+ mkdirSync(backupDirectory, { recursive: true });
263
+ renameSync(sourceChild, join(backupDirectory, eachEntry.name));
264
+ console.log(` Kept the local copy of ${sourceChild} in ${backupDirectory}`);
265
+ }
266
+ }
267
+
150
268
  /**
151
269
  * Move unique entries from sourceDirectory into destinationDirectory.
152
270
  *
@@ -12,6 +12,7 @@ import {
12
12
  readFileSync,
13
13
  realpathSync,
14
14
  rmSync,
15
+ symlinkSync,
15
16
  writeFileSync,
16
17
  } from 'node:fs';
17
18
  import { tmpdir } from 'node:os';
@@ -23,6 +24,7 @@ import {
23
24
  POINTER_ACTION_CREATED,
24
25
  directoryPointerTypeForPlatform,
25
26
  ensureDirectoryPointer,
27
+ ensureLinkedSkillFolder,
26
28
  isDirectoryPointerTo,
27
29
  unlinkDirectoryPointerIfMatch,
28
30
  } from './publish-directory-pointer.mjs';
@@ -36,6 +38,15 @@ function makeSandbox() {
36
38
  };
37
39
  }
38
40
 
41
+ function entryExistsWithoutFollowing(entryPath) {
42
+ try {
43
+ lstatSync(entryPath);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+
39
50
  test('directoryPointerTypeForPlatform uses a junction on Windows and a dir pointer elsewhere', () => {
40
51
  assert.equal(directoryPointerTypeForPlatform('win32'), DIRECTORY_POINTER_TYPE_JUNCTION);
41
52
  assert.equal(directoryPointerTypeForPlatform('linux'), DIRECTORY_POINTER_TYPE_DIR);
@@ -127,3 +138,152 @@ test('unlinkDirectoryPointerIfMatch removes only a pointer that aims at the expe
127
138
  rmSync(sandbox.root, { recursive: true, force: true });
128
139
  }
129
140
  });
141
+
142
+ test('ensureLinkedSkillFolder replaces a pointer with a folder that links each shipped skill', () => {
143
+ const sandbox = makeSandbox();
144
+ const pluginCacheSkill = join(sandbox.root, 'plugins', 'cache', 'plugin-skill');
145
+ try {
146
+ mkdirSync(join(sandbox.targetPath, 'shipped-skill'), { recursive: true });
147
+ writeFileSync(join(sandbox.targetPath, 'shipped-skill', 'SKILL.md'), 'shipped body\n');
148
+ mkdirSync(pluginCacheSkill, { recursive: true });
149
+ symlinkSync(pluginCacheSkill, join(sandbox.targetPath, 'plugin-skill'), 'dir');
150
+ ensureDirectoryPointer(sandbox.pointerPath, sandbox.targetPath);
151
+
152
+ const { createdLinkPaths } = ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
153
+
154
+ assert.equal(lstatSync(sandbox.pointerPath).isDirectory(), true);
155
+ assert.equal(lstatSync(sandbox.pointerPath).isSymbolicLink(), false);
156
+ assert.equal(lstatSync(join(sandbox.pointerPath, 'shipped-skill')).isSymbolicLink(), true);
157
+ assert.equal(
158
+ isDirectoryPointerTo(
159
+ join(sandbox.pointerPath, 'shipped-skill'),
160
+ join(sandbox.targetPath, 'shipped-skill'),
161
+ ),
162
+ true,
163
+ );
164
+ assert.equal(
165
+ readFileSync(join(sandbox.pointerPath, 'shipped-skill', 'SKILL.md'), 'utf8'),
166
+ 'shipped body\n',
167
+ );
168
+ assert.equal(entryExistsWithoutFollowing(join(sandbox.pointerPath, 'plugin-skill')), false);
169
+ assert.deepEqual(createdLinkPaths, [join(sandbox.pointerPath, 'shipped-skill')]);
170
+ } finally {
171
+ rmSync(sandbox.root, { recursive: true, force: true });
172
+ }
173
+ });
174
+
175
+ test('ensureLinkedSkillFolder keeps a personal skill that exists only in the lookup folder', () => {
176
+ const sandbox = makeSandbox();
177
+ try {
178
+ mkdirSync(join(sandbox.pointerPath, 'personal-skill'), { recursive: true });
179
+ writeFileSync(join(sandbox.pointerPath, 'personal-skill', 'notes.md'), 'personal\n');
180
+ mkdirSync(sandbox.targetPath, { recursive: true });
181
+
182
+ const { createdLinkPaths } = ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
183
+
184
+ assert.equal(lstatSync(join(sandbox.pointerPath, 'personal-skill')).isDirectory(), true);
185
+ assert.equal(lstatSync(join(sandbox.pointerPath, 'personal-skill')).isSymbolicLink(), false);
186
+ assert.equal(existsSync(join(sandbox.targetPath, 'personal-skill')), false);
187
+ assert.equal(
188
+ readFileSync(join(sandbox.pointerPath, 'personal-skill', 'notes.md'), 'utf8'),
189
+ 'personal\n',
190
+ );
191
+ assert.deepEqual(createdLinkPaths, []);
192
+ } finally {
193
+ rmSync(sandbox.root, { recursive: true, force: true });
194
+ }
195
+ });
196
+
197
+ test('ensureLinkedSkillFolder removes a dangling link into the install folder and keeps a link to another folder', () => {
198
+ const sandbox = makeSandbox();
199
+ const otherSkill = join(sandbox.root, 'elsewhere', 'other-skill');
200
+ try {
201
+ mkdirSync(sandbox.targetPath, { recursive: true });
202
+ mkdirSync(sandbox.pointerPath, { recursive: true });
203
+ symlinkSync(join(sandbox.targetPath, 'retired-skill'), join(sandbox.pointerPath, 'retired-skill'), 'dir');
204
+ mkdirSync(otherSkill, { recursive: true });
205
+ symlinkSync(otherSkill, join(sandbox.pointerPath, 'other-skill'), 'dir');
206
+
207
+ ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
208
+
209
+ assert.equal(entryExistsWithoutFollowing(join(sandbox.pointerPath, 'retired-skill')), false);
210
+ assert.equal(lstatSync(join(sandbox.pointerPath, 'other-skill')).isSymbolicLink(), true);
211
+ } finally {
212
+ rmSync(sandbox.root, { recursive: true, force: true });
213
+ }
214
+ });
215
+
216
+ test('ensureLinkedSkillFolder creates no links on a second call and still reports the link in place', () => {
217
+ const sandbox = makeSandbox();
218
+ try {
219
+ mkdirSync(join(sandbox.targetPath, 'shipped-skill'), { recursive: true });
220
+ writeFileSync(join(sandbox.targetPath, 'shipped-skill', 'SKILL.md'), 'shipped body\n');
221
+ ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
222
+
223
+ const secondCall = ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
224
+
225
+ assert.deepEqual(secondCall.createdLinkPaths, []);
226
+ assert.deepEqual(secondCall.linkPaths, [join(sandbox.pointerPath, 'shipped-skill')]);
227
+ assert.equal(
228
+ isDirectoryPointerTo(
229
+ join(sandbox.pointerPath, 'shipped-skill'),
230
+ join(sandbox.targetPath, 'shipped-skill'),
231
+ ),
232
+ true,
233
+ );
234
+ } finally {
235
+ rmSync(sandbox.root, { recursive: true, force: true });
236
+ }
237
+ });
238
+
239
+ test('ensureLinkedSkillFolder replaces a lookup link that aims at another directory and leaves that directory alone', () => {
240
+ const sandbox = makeSandbox();
241
+ const elsewhere = join(sandbox.root, 'elsewhere');
242
+ try {
243
+ mkdirSync(join(sandbox.targetPath, 'shipped-skill'), { recursive: true });
244
+ writeFileSync(join(sandbox.targetPath, 'shipped-skill', 'SKILL.md'), 'shipped body\n');
245
+ mkdirSync(elsewhere, { recursive: true });
246
+ writeFileSync(join(elsewhere, 'notes.md'), 'elsewhere\n');
247
+ mkdirSync(join(sandbox.root, 'lookup'), { recursive: true });
248
+ symlinkSync(elsewhere, sandbox.pointerPath, 'dir');
249
+
250
+ const { createdLinkPaths } = ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath);
251
+
252
+ assert.equal(lstatSync(sandbox.pointerPath).isDirectory(), true);
253
+ assert.equal(lstatSync(sandbox.pointerPath).isSymbolicLink(), false);
254
+ assert.equal(isDirectoryPointerTo(join(sandbox.pointerPath, 'shipped-skill'), join(sandbox.targetPath, 'shipped-skill')), true);
255
+ assert.deepEqual(createdLinkPaths, [join(sandbox.pointerPath, 'shipped-skill')]);
256
+ assert.equal(readFileSync(join(elsewhere, 'notes.md'), 'utf8'), 'elsewhere\n');
257
+ } finally {
258
+ rmSync(sandbox.root, { recursive: true, force: true });
259
+ }
260
+ });
261
+
262
+ test('ensureLinkedSkillFolder moves a lookup file that conflicts with the agents home into the backup folder', () => {
263
+ const sandbox = makeSandbox();
264
+ const conflictBackup = join(sandbox.root, 'backup', 'skills');
265
+ try {
266
+ mkdirSync(join(sandbox.targetPath, 'shared-skill'), { recursive: true });
267
+ writeFileSync(join(sandbox.targetPath, 'shared-skill', 'SKILL.md'), 'agents home body\n');
268
+ mkdirSync(join(sandbox.pointerPath, 'shared-skill'), { recursive: true });
269
+ writeFileSync(join(sandbox.pointerPath, 'shared-skill', 'SKILL.md'), 'local edit\n');
270
+ writeFileSync(join(sandbox.pointerPath, 'shared-skill', 'extra.md'), 'lookup only\n');
271
+
272
+ ensureLinkedSkillFolder(sandbox.pointerPath, sandbox.targetPath, conflictBackup);
273
+
274
+ assert.equal(
275
+ readFileSync(join(conflictBackup, 'shared-skill', 'SKILL.md'), 'utf8'),
276
+ 'local edit\n',
277
+ );
278
+ assert.equal(
279
+ readFileSync(join(sandbox.targetPath, 'shared-skill', 'extra.md'), 'utf8'),
280
+ 'lookup only\n',
281
+ );
282
+ assert.equal(
283
+ readFileSync(join(sandbox.pointerPath, 'shared-skill', 'SKILL.md'), 'utf8'),
284
+ 'agents home body\n',
285
+ );
286
+ } finally {
287
+ rmSync(sandbox.root, { recursive: true, force: true });
288
+ }
289
+ });
@@ -40,6 +40,6 @@ When you cannot prove it, leave the pull request unopened. Tell the owner in thr
40
40
 
41
41
  `hooks/blocking/pull_request_proof.py` reads the body of each new pull request before it opens. `pr_lifecycle_skill_gate.py` runs it on `gh pr create`, the `pull_request.py create` script, and each `mcp__*__create_pull_request` tool. The gate denies the call when the body has no "Proof in practice" heading, or when the text under that heading names no command in backticks. The gate also denies a section whose only commands run a test runner, such as `pytest`, `python -m unittest`, `uv run pytest`, `npm test`, `npx vitest`, `jest`, `go test` or `cargo test`. Quotes around a runner word, interpreter flags before `-m`, and `coverage run -m unittest` are still test runs. A command is an inline backticked span or a `$ ` line inside a fenced block. A span that starts with a path and line, such as `gate.py:12`, is not a command. A span that holds one path or file name, such as `src/x.py`, is not a command unless that span runs a test runner, such as `py.test` or `pytest.exe`. A test run piped into `tee`, `tail`, `head`, `grep` or `cat` is still a test run. The deny quotes the line "Unit tests are welcome as extra evidence. The live run is the proof." and asks for a run of the changed thing the way its user runs it, without the change and with it. The gate also denies a section whose prose says part of the change is not proven, not tested or not verified, with "yet", "been" or "fully" allowed after the "not", or says unproven, untested or unverified. The deny quotes that line, and asks for the run before the pull request opens, or for the line under a "Not covered" heading when the change does not target it. The same denial covers a proof line that opens with "not run", "not exercised" or "not executed" (a "yet" or "been" may follow the "not") or says "has not been run". A proof line with a merge word (merge, merged, merges or merging, so post-merge too) is denied with its own reason: run the check on the branch, and put a file or command name that contains merge in backticks. A step that needs the merged code to exist goes under a "Not covered" heading at the same level as the proof heading, as a line that opens with "not run". `UNPROVEN_ADMISSION_PATTERN` and `MERGE_WORD_PATTERN` list the shapes. Words inside backticks or a fenced block are quoted output and do not count. A section with one command that is not a test run, and no such line, passes. A `gh pr create` with no `--body` or `--body-file` is denied with a request for the body. A body edit through `update_pull_request`, `gh pr edit` or the `pull_request.py edit` script gets the same checks on its proof section that a new pull request gets, so an edit cannot swap in a proof that a new pull request would be denied. An edit with no proof section passes. A body the gate cannot read passes, such as an inline multi-line `--body`, a body from standard input, or a body written through `gh api`. Merges and pushes pass.
42
42
 
43
- When the checked-out branch changes a file people see (`.html`, `.htm`, `.css`, `.scss`, `.tsx`, `.jsx`, `.vue`, `.svelte`), the gate also denies a body whose proof section holds no picture: a markdown image, an image URL, or an Artifact page link that shows the screenshots. Render the change, read the screenshot, and put it in the section, so the reader sees what you looked at. When git in the session directory cannot list the branch's changed files, the gate asks for the picture as well.
43
+ When the checked-out branch changes a file people see (`.html`, `.htm`, `.css`, `.scss`, `.tsx`, `.jsx`, `.vue`, `.svelte`), the gate also denies a body whose proof section holds no picture: a markdown image, an image URL, or an Artifact page link that shows the screenshots. Render the change, read the screenshot, and put it in the section, so the reader sees what you looked at. A page the branch only moves to another folder or name that ends the same way, with every byte kept (`R100` in `git diff --name-status`), changes nothing people see, so the gate leaves it out; a moved page that also changed, or a file that becomes a page by a change of name ending, still needs the picture. When git in the session directory cannot list the branch's changed files, the gate asks for the picture as well.
44
44
 
45
45
  The gate checks that the section is there, names a command, and admits no unproven part. Whether the run proves the change stays a judgment for the author and the reviewer.
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import re
6
7
  import subprocess
7
8
  import sys
@@ -31,7 +32,7 @@ from hooks_constants.pull_request_proof_constants import (
31
32
  BASE_FLAG_ASSIGNMENT_PREFIX,
32
33
  COMPARE_ENDPOINT_TEMPLATE,
33
34
  COMPARE_FILE_LIST_LIMIT,
34
- COMPARE_FILE_NAMES_QUERY,
35
+ COMPARE_FILE_STATUS_QUERY,
35
36
  DEFAULT_BRANCH_QUERY,
36
37
  GH_TIMEOUT_SECONDS,
37
38
  HEAD_FLAG_ASSIGNMENT_PREFIX,
@@ -51,6 +52,12 @@ from hooks_constants.pull_request_proof_constants import (
51
52
  MISSING_PROOF_REASON,
52
53
  NEXT_HEADING_PATTERN,
53
54
  PROOF_HEADING_PATTERN,
55
+ PURE_RENAME_STATUS,
56
+ RAW_HEADER_FIELD_COUNT,
57
+ RAW_RECORD_PREFIX,
58
+ RAW_RENAME_PATH_COUNT,
59
+ RAW_RENAME_STATUS_LETTER,
60
+ ALL_RAW_TWO_PATH_STATUS_LETTERS,
54
61
  PROOF_IMAGE_PATTERN,
55
62
  PULL_REQUEST_SCRIPT_CREATE_WORD,
56
63
  PULL_REQUEST_SCRIPT_EDIT_WORD,
@@ -626,18 +633,31 @@ def missing_existing_work_reason(all_payload_fields: Mapping[str, object]) -> st
626
633
  return None
627
634
 
628
635
 
629
- def _git_lines(working_directory: str, *all_git_arguments: str) -> list[str] | None:
636
+ class ChangedFile(NamedTuple):
637
+ path: str
638
+ old_path: str
639
+ is_pure_rename: bool
640
+
641
+
642
+ def _git_output(working_directory: str, *all_git_arguments: str) -> str | None:
630
643
  try:
631
644
  completed = subprocess.run(
632
645
  ["git", "-C", working_directory, *all_git_arguments],
633
646
  capture_output=True,
634
647
  text=True,
648
+ encoding="utf-8",
649
+ errors="replace",
635
650
  timeout=GIT_TIMEOUT_SECONDS,
636
651
  check=False,
637
652
  )
638
653
  except (OSError, subprocess.SubprocessError):
639
654
  return None
640
- return completed.stdout.splitlines() if completed.returncode == 0 else None
655
+ return completed.stdout if completed.returncode == 0 else None
656
+
657
+
658
+ def _git_lines(working_directory: str, *all_git_arguments: str) -> list[str] | None:
659
+ output = _git_output(working_directory, *all_git_arguments)
660
+ return output.splitlines() if output is not None else None
641
661
 
642
662
 
643
663
  def _first_merge_base(working_directory: str, head_reference: str) -> str | None:
@@ -667,9 +687,16 @@ def visible_changed_files(working_directory: str, head_branch: object) -> list[s
667
687
  origin/HEAD, origin/main and main that git can reach::
668
688
 
669
689
  checkout on feature, page.html changed -> ["page.html"]
690
+ page.html renamed with no edit -> []
691
+ page.html renamed and edited -> ["page.html"]
670
692
  named head exists nowhere in the clone -> None
671
693
  no base reference reachable -> None
672
694
 
695
+ A rename whose old and new blob ids match and whose old and new names end the
696
+ same way, such as a.html to b/a.html, changes nothing people see. One that
697
+ changes the ending, such as notes.txt or Widget.tsx to page.html, still makes a
698
+ page. A copy or a rename with an edit keeps its path.
699
+
673
700
  Args:
674
701
  working_directory: The session directory the hook payload names.
675
702
  head_branch: The head branch a create call names, or None.
@@ -682,14 +709,64 @@ def visible_changed_files(working_directory: str, head_branch: object) -> list[s
682
709
  merge_base = _first_merge_base(working_directory, head_reference)
683
710
  if merge_base is None:
684
711
  return None
685
- all_changed_paths = _git_lines(working_directory, "diff", "--name-only", merge_base, head_reference)
686
- if all_changed_paths is None:
712
+ raw_output = _git_output(working_directory, "diff", "--raw", "--no-abbrev", "-M", "-z", merge_base, head_reference)
713
+ if raw_output is None:
714
+ return None
715
+ all_changes = _git_changes(raw_output.split("\0"))
716
+ if all_changes is None:
717
+ return None
718
+ return _visible_paths(all_changes)
719
+
720
+
721
+ def _git_changes(all_raw_fields: list[str]) -> list[ChangedFile] | None:
722
+ all_changes = []
723
+ field_index = 0
724
+ while field_index < len(all_raw_fields) and all_raw_fields[field_index].startswith(RAW_RECORD_PREFIX):
725
+ all_header_fields = all_raw_fields[field_index][1:].split(" ")
726
+ if len(all_header_fields) != RAW_HEADER_FIELD_COUNT:
727
+ return None
728
+ old_mode, new_mode, old_blob, new_blob, status = all_header_fields
729
+ path_count = RAW_RENAME_PATH_COUNT if status[:1] in ALL_RAW_TWO_PATH_STATUS_LETTERS else 1
730
+ all_paths = all_raw_fields[field_index + 1 : field_index + 1 + path_count]
731
+ if len(all_paths) != path_count:
732
+ return None
733
+ is_pure_rename = status.startswith(RAW_RENAME_STATUS_LETTER) and old_mode == new_mode and old_blob == new_blob
734
+ all_changes.append(ChangedFile(path=all_paths[-1], old_path=all_paths[0], is_pure_rename=is_pure_rename))
735
+ field_index += 1 + path_count
736
+ if any(all_raw_fields[field_index:]):
687
737
  return None
688
- return _visible_paths(all_changed_paths)
738
+ return all_changes
689
739
 
690
740
 
691
- def _visible_paths(all_changed_paths: list[str]) -> list[str]:
692
- return [each_path for each_path in all_changed_paths if each_path.lower().endswith(ALL_VISIBLE_FILE_SUFFIXES)]
741
+ def _compare_changes(all_json_lines: list[str]) -> list[ChangedFile] | None:
742
+ all_changes = []
743
+ for each_line in all_json_lines:
744
+ try:
745
+ status, old_path, path = json.loads(each_line)
746
+ except (ValueError, TypeError):
747
+ return None
748
+ all_changes.append(ChangedFile(path=path, old_path=old_path, is_pure_rename=status == PURE_RENAME_STATUS))
749
+ return all_changes
750
+
751
+
752
+ def _visible_suffix(path: str) -> str | None:
753
+ lowered_path = path.lower()
754
+ for each_suffix in ALL_VISIBLE_FILE_SUFFIXES:
755
+ if lowered_path.endswith(each_suffix):
756
+ return each_suffix
757
+ return None
758
+
759
+
760
+ def _is_unchanged_move(change: ChangedFile) -> bool:
761
+ return change.is_pure_rename and _visible_suffix(change.old_path) == _visible_suffix(change.path)
762
+
763
+
764
+ def _visible_paths(all_changes: list[ChangedFile]) -> list[str]:
765
+ return [
766
+ each_change.path
767
+ for each_change in all_changes
768
+ if _visible_suffix(each_change.path) is not None and not _is_unchanged_move(each_change)
769
+ ]
693
770
 
694
771
 
695
772
  def _gh_api_lines(endpoint: str, query: str) -> list[str] | None:
@@ -698,6 +775,8 @@ def _gh_api_lines(endpoint: str, query: str) -> list[str] | None:
698
775
  ["gh", "api", endpoint, "--jq", query],
699
776
  capture_output=True,
700
777
  text=True,
778
+ encoding="utf-8",
779
+ errors="replace",
701
780
  timeout=GH_TIMEOUT_SECONDS,
702
781
  check=False,
703
782
  )
@@ -718,16 +797,19 @@ def _compare_base_branch(repository: str, base_branch: str | None) -> str | None
718
797
 
719
798
 
720
799
  def _visible_compare_paths(repository: str, base_branch: str, head_branch: str) -> list[str] | None:
721
- all_changed_paths = _gh_api_lines(
800
+ all_status_lines = _gh_api_lines(
722
801
  COMPARE_ENDPOINT_TEMPLATE.format(
723
802
  repository=repository, base_branch=base_branch, head_branch=head_branch
724
803
  ),
725
- COMPARE_FILE_NAMES_QUERY,
804
+ COMPARE_FILE_STATUS_QUERY,
726
805
  )
727
- if all_changed_paths is None:
806
+ if all_status_lines is None:
807
+ return None
808
+ all_changes = _compare_changes(all_status_lines)
809
+ if all_changes is None:
728
810
  return None
729
- all_visible_paths = _visible_paths(all_changed_paths)
730
- if all_visible_paths or len(all_changed_paths) < COMPARE_FILE_LIST_LIMIT:
811
+ all_visible_paths = _visible_paths(all_changes)
812
+ if all_visible_paths or len(all_status_lines) < COMPARE_FILE_LIST_LIMIT:
731
813
  return all_visible_paths
732
814
  return None
733
815
 
@@ -741,13 +823,15 @@ def remote_visible_changed_files(
741
823
 
742
824
  compare lists tool.py -> []
743
825
  compare lists web/page.html -> ["web/page.html"]
826
+ compare lists web/page.html renamed, no edit -> []
744
827
  compare returns 300 paths and none are visible -> None
745
828
  repository or head missing -> None
746
829
 
747
830
  The base is the named base branch, else the repository's default branch.
748
831
  A page of 300 paths is the compare API's file cap. A visible file on that
749
832
  page is returned. A full page with none is None, because a later file can
750
- still be one people see.
833
+ still be one people see. A pure rename counts toward the 300. It is not
834
+ visible when the file it moved from ended the same way.
751
835
 
752
836
  Args:
753
837
  repository: The owner/name the create call names, or None.