@deepseek-ai/dsh-experimental-client-ui-forge 0.2.2-alpha.3 → 0.2.2-rc.2

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.
Files changed (272) hide show
  1. package/README.i18n.yaml +8 -8
  2. package/README.md +41 -14
  3. package/README.zh.md +40 -13
  4. package/lib/client.js +13 -11800
  5. package/lib/client.js.map +1 -0
  6. package/lib/index.js +1340 -115
  7. package/lib/typert.host.js +1715 -212
  8. package/lib/typert.remote-client.d.ts +42 -5
  9. package/lib/typert.remote-client.d.ts.map +1 -0
  10. package/lib/typert.remote-client.js +1523 -244
  11. package/lib/types/client/ActionToast.d.ts.map +1 -0
  12. package/lib/types/client/ActionToast.js.map +1 -0
  13. package/lib/types/client/BaseMenu.d.ts +30 -0
  14. package/lib/types/client/BaseMenu.d.ts.map +1 -0
  15. package/lib/types/client/BaseMenu.js.map +1 -0
  16. package/lib/types/client/ChangeRequestCard.d.ts +9 -5
  17. package/lib/types/client/ChangeRequestCard.d.ts.map +1 -0
  18. package/lib/types/client/ChangeRequestCard.js.map +1 -0
  19. package/lib/types/client/ChangeRequestOverview.d.ts +124 -0
  20. package/lib/types/client/ChangeRequestOverview.d.ts.map +1 -0
  21. package/lib/types/client/ChangeRequestOverview.js.map +1 -0
  22. package/lib/types/client/ChangedFiles.d.ts +2 -0
  23. package/lib/types/client/ChangedFiles.d.ts.map +1 -0
  24. package/lib/types/client/ChangedFiles.js.map +1 -0
  25. package/lib/types/client/ChangesTab.d.ts +30 -5
  26. package/lib/types/client/ChangesTab.d.ts.map +1 -0
  27. package/lib/types/client/ChangesTab.js.map +1 -0
  28. package/lib/types/client/ChangesTabTitle.d.ts.map +1 -0
  29. package/lib/types/client/ChangesTabTitle.js.map +1 -0
  30. package/lib/types/client/CommitMenu.d.ts +41 -0
  31. package/lib/types/client/CommitMenu.d.ts.map +1 -0
  32. package/lib/types/client/CommitMenu.js.map +1 -0
  33. package/lib/types/client/DiffFile.d.ts +47 -15
  34. package/lib/types/client/DiffFile.d.ts.map +1 -0
  35. package/lib/types/client/DiffFile.js.map +1 -0
  36. package/lib/types/client/FileLabel.d.ts.map +1 -0
  37. package/lib/types/client/FileLabel.js.map +1 -0
  38. package/lib/types/client/FileTreePane.d.ts +4 -2
  39. package/lib/types/client/FileTreePane.d.ts.map +1 -0
  40. package/lib/types/client/FileTreePane.js.map +1 -0
  41. package/lib/types/client/ForgeTab.d.ts +9 -1
  42. package/lib/types/client/ForgeTab.d.ts.map +1 -0
  43. package/lib/types/client/ForgeTab.js.map +1 -0
  44. package/lib/types/client/ForgeTabTitle.d.ts.map +1 -0
  45. package/lib/types/client/ForgeTabTitle.js.map +1 -0
  46. package/lib/types/client/HeaderButton.d.ts.map +1 -0
  47. package/lib/types/client/HeaderButton.js.map +1 -0
  48. package/lib/types/client/LocalChangesCard.d.ts.map +1 -0
  49. package/lib/types/client/LocalChangesCard.js.map +1 -0
  50. package/lib/types/client/RefreshGlyph.d.ts.map +1 -0
  51. package/lib/types/client/RefreshGlyph.js.map +1 -0
  52. package/lib/types/client/ReviewComposer.d.ts +20 -6
  53. package/lib/types/client/ReviewComposer.d.ts.map +1 -0
  54. package/lib/types/client/ReviewComposer.js.map +1 -0
  55. package/lib/types/client/ReviewControls.d.ts +79 -0
  56. package/lib/types/client/ReviewControls.d.ts.map +1 -0
  57. package/lib/types/client/ReviewControls.js.map +1 -0
  58. package/lib/types/client/ReviewThread.d.ts +4 -4
  59. package/lib/types/client/ReviewThread.d.ts.map +1 -0
  60. package/lib/types/client/ReviewThread.js.map +1 -0
  61. package/lib/types/client/ReviewThreads.d.ts +108 -0
  62. package/lib/types/client/ReviewThreads.d.ts.map +1 -0
  63. package/lib/types/client/ReviewThreads.js.map +1 -0
  64. package/lib/types/client/SessionHoverForge.d.ts.map +1 -0
  65. package/lib/types/client/SessionHoverForge.js.map +1 -0
  66. package/lib/types/client/SessionRowForge.d.ts +1 -1
  67. package/lib/types/client/SessionRowForge.d.ts.map +1 -0
  68. package/lib/types/client/SessionRowForge.js.map +1 -0
  69. package/lib/types/client/SubmitReview.d.ts +12 -4
  70. package/lib/types/client/SubmitReview.d.ts.map +1 -0
  71. package/lib/types/client/SubmitReview.js.map +1 -0
  72. package/lib/types/client/ThreadList.d.ts +43 -0
  73. package/lib/types/client/ThreadList.d.ts.map +1 -0
  74. package/lib/types/client/ThreadList.js.map +1 -0
  75. package/lib/types/client/ViewOptionsMenu.d.ts +31 -0
  76. package/lib/types/client/ViewOptionsMenu.d.ts.map +1 -0
  77. package/lib/types/client/ViewOptionsMenu.js.map +1 -0
  78. package/lib/types/client/WorktreeProgress.d.ts.map +1 -0
  79. package/lib/types/client/WorktreeProgress.js.map +1 -0
  80. package/lib/types/client/WorktreeSettings.d.ts +12 -0
  81. package/lib/types/client/WorktreeSettings.d.ts.map +1 -0
  82. package/lib/types/client/WorktreeSettings.js.map +1 -0
  83. package/lib/types/client/WorktreeToggle.d.ts.map +1 -0
  84. package/lib/types/client/WorktreeToggle.js.map +1 -0
  85. package/lib/types/client/changes-address.d.ts.map +1 -0
  86. package/lib/types/client/changes-address.js.map +1 -0
  87. package/lib/types/client/changes-store.d.ts +20 -5
  88. package/lib/types/client/changes-store.d.ts.map +1 -0
  89. package/lib/types/client/changes-store.js.map +1 -0
  90. package/lib/types/client/checkout.d.ts.map +1 -0
  91. package/lib/types/client/checkout.js.map +1 -0
  92. package/lib/types/client/code-selection.d.ts.map +1 -0
  93. package/lib/types/client/code-selection.js.map +1 -0
  94. package/lib/types/client/diff-rows.d.ts.map +1 -0
  95. package/lib/types/client/diff-rows.js.map +1 -0
  96. package/lib/types/client/file-tree.d.ts.map +1 -0
  97. package/lib/types/client/file-tree.js.map +1 -0
  98. package/lib/types/client/format.d.ts.map +1 -0
  99. package/lib/types/client/format.js.map +1 -0
  100. package/lib/types/client/glyphs.d.ts +4 -2
  101. package/lib/types/client/glyphs.d.ts.map +1 -0
  102. package/lib/types/client/glyphs.js.map +1 -0
  103. package/lib/types/client/host-viewed.d.ts +84 -0
  104. package/lib/types/client/host-viewed.d.ts.map +1 -0
  105. package/lib/types/client/host-viewed.js.map +1 -0
  106. package/lib/types/client/index.d.ts.map +1 -0
  107. package/lib/types/client/index.js.map +1 -0
  108. package/lib/types/client/locales.d.ts +175 -3
  109. package/lib/types/client/locales.d.ts.map +1 -0
  110. package/lib/types/client/locales.js.map +1 -0
  111. package/lib/types/client/menu-search.d.ts +10 -0
  112. package/lib/types/client/menu-search.d.ts.map +1 -0
  113. package/lib/types/client/menu-search.js.map +1 -0
  114. package/lib/types/client/mount.d.ts +4 -0
  115. package/lib/types/client/mount.d.ts.map +1 -0
  116. package/lib/types/client/mount.js.map +1 -0
  117. package/lib/types/client/review-queue.d.ts +5 -8
  118. package/lib/types/client/review-queue.d.ts.map +1 -0
  119. package/lib/types/client/review-queue.js.map +1 -0
  120. package/lib/types/client/review-threads.d.ts +108 -0
  121. package/lib/types/client/review-threads.d.ts.map +1 -0
  122. package/lib/types/client/review-threads.js.map +1 -0
  123. package/lib/types/client/review.d.ts +31 -4
  124. package/lib/types/client/review.d.ts.map +1 -0
  125. package/lib/types/client/review.js.map +1 -0
  126. package/lib/types/client/section-reach.d.ts +26 -0
  127. package/lib/types/client/section-reach.d.ts.map +1 -0
  128. package/lib/types/client/section-reach.js.map +1 -0
  129. package/lib/types/client/session-list.d.ts.map +1 -0
  130. package/lib/types/client/session-list.js.map +1 -0
  131. package/lib/types/client/source.d.ts.map +1 -0
  132. package/lib/types/client/source.js.map +1 -0
  133. package/lib/types/client/status.d.ts.map +1 -0
  134. package/lib/types/client/status.js.map +1 -0
  135. package/lib/types/client/thread-state.d.ts +68 -0
  136. package/lib/types/client/thread-state.d.ts.map +1 -0
  137. package/lib/types/client/thread-state.js.map +1 -0
  138. package/lib/types/client/toolbar-fold.d.ts +19 -0
  139. package/lib/types/client/toolbar-fold.d.ts.map +1 -0
  140. package/lib/types/client/toolbar-fold.js.map +1 -0
  141. package/lib/types/client/viewed-files.d.ts +70 -0
  142. package/lib/types/client/viewed-files.d.ts.map +1 -0
  143. package/lib/types/client/viewed-files.js.map +1 -0
  144. package/lib/types/client/worktree-settings-form.d.ts +32 -0
  145. package/lib/types/client/worktree-settings-form.d.ts.map +1 -0
  146. package/lib/types/client/worktree-settings-form.js.map +1 -0
  147. package/lib/types/commit-range.d.ts +17 -0
  148. package/lib/types/commit-range.d.ts.map +1 -0
  149. package/lib/types/commit-range.js.map +1 -0
  150. package/lib/types/diff.d.ts +10 -2
  151. package/lib/types/diff.d.ts.map +1 -0
  152. package/lib/types/diff.js.map +1 -0
  153. package/lib/types/git.d.ts.map +1 -0
  154. package/lib/types/git.js.map +1 -0
  155. package/lib/types/index.d.ts +194 -14
  156. package/lib/types/index.d.ts.map +1 -0
  157. package/lib/types/index.js.map +1 -0
  158. package/lib/types/layers.d.ts +66 -0
  159. package/lib/types/layers.d.ts.map +1 -0
  160. package/lib/types/layers.js.map +1 -0
  161. package/lib/types/local-diff.d.ts +54 -6
  162. package/lib/types/local-diff.d.ts.map +1 -0
  163. package/lib/types/local-diff.js.map +1 -0
  164. package/lib/types/panel.d.ts.map +1 -0
  165. package/lib/types/panel.js.map +1 -0
  166. package/lib/types/parse.d.ts +16 -0
  167. package/lib/types/parse.d.ts.map +1 -0
  168. package/lib/types/parse.js.map +1 -0
  169. package/lib/types/patch-cache.d.ts +12 -7
  170. package/lib/types/patch-cache.d.ts.map +1 -0
  171. package/lib/types/patch-cache.js.map +1 -0
  172. package/lib/types/review-cache.d.ts +54 -0
  173. package/lib/types/review-cache.d.ts.map +1 -0
  174. package/lib/types/review-cache.js.map +1 -0
  175. package/lib/types/states.d.ts.map +1 -0
  176. package/lib/types/states.js.map +1 -0
  177. package/lib/types/types.d.ts +113 -11
  178. package/lib/types/types.d.ts.map +1 -0
  179. package/lib/types/types.js.map +1 -0
  180. package/lib/types/wildmatch.d.ts +14 -0
  181. package/lib/types/wildmatch.d.ts.map +1 -0
  182. package/lib/types/wildmatch.js.map +1 -0
  183. package/lib/types/worktree.d.ts +8 -6
  184. package/lib/types/worktree.d.ts.map +1 -0
  185. package/lib/types/worktree.js.map +1 -0
  186. package/package.json +59 -49
  187. package/src/client/ActionToast.tsx +38 -0
  188. package/src/client/BaseMenu.module.css +153 -0
  189. package/src/client/BaseMenu.tsx +180 -0
  190. package/src/client/ChangeRequestCard.tsx +439 -0
  191. package/src/client/ChangeRequestOverview.module.css +196 -0
  192. package/src/client/ChangeRequestOverview.tsx +620 -0
  193. package/src/client/ChangedFiles.module.css +26 -0
  194. package/src/client/ChangedFiles.tsx +144 -0
  195. package/src/client/ChangesTab.module.css +984 -0
  196. package/src/client/ChangesTab.tsx +1288 -0
  197. package/src/client/ChangesTabTitle.tsx +28 -0
  198. package/src/client/CommitMenu.module.css +139 -0
  199. package/src/client/CommitMenu.tsx +186 -0
  200. package/src/client/DiffFile.tsx +621 -0
  201. package/src/client/FileLabel.module.css +53 -0
  202. package/src/client/FileLabel.tsx +66 -0
  203. package/src/client/FileTreePane.module.css +10 -0
  204. package/src/client/FileTreePane.tsx +79 -0
  205. package/src/client/ForgeTab.module.css +627 -0
  206. package/src/client/ForgeTab.tsx +263 -0
  207. package/src/client/ForgeTabTitle.tsx +21 -0
  208. package/src/client/HeaderButton.module.css +29 -0
  209. package/src/client/HeaderButton.tsx +68 -0
  210. package/src/client/LocalChangesCard.tsx +83 -0
  211. package/src/client/RefreshGlyph.module.css +22 -0
  212. package/src/client/RefreshGlyph.tsx +35 -0
  213. package/src/client/ReviewComposer.module.css +37 -0
  214. package/src/client/ReviewComposer.tsx +128 -0
  215. package/src/client/ReviewControls.module.css +162 -0
  216. package/src/client/ReviewControls.tsx +191 -0
  217. package/src/client/ReviewThread.tsx +96 -0
  218. package/src/client/ReviewThreads.module.css +326 -0
  219. package/src/client/ReviewThreads.tsx +443 -0
  220. package/src/client/SessionHoverForge.tsx +72 -0
  221. package/src/client/SessionList.module.css +85 -0
  222. package/src/client/SessionRowForge.tsx +86 -0
  223. package/src/client/SubmitReview.module.css +26 -0
  224. package/src/client/SubmitReview.tsx +95 -0
  225. package/src/client/ThreadList.module.css +218 -0
  226. package/src/client/ThreadList.tsx +165 -0
  227. package/src/client/ViewOptionsMenu.tsx +79 -0
  228. package/src/client/WorktreeProgress.module.css +226 -0
  229. package/src/client/WorktreeProgress.tsx +280 -0
  230. package/src/client/WorktreeSettings.module.css +29 -0
  231. package/src/client/WorktreeSettings.tsx +42 -0
  232. package/src/client/WorktreeToggle.module.css +132 -0
  233. package/src/client/WorktreeToggle.tsx +165 -0
  234. package/src/client/changes-address.ts +110 -0
  235. package/src/client/changes-store.ts +155 -0
  236. package/src/client/checkout.ts +75 -0
  237. package/src/client/code-selection.ts +53 -0
  238. package/src/client/diff-rows.ts +199 -0
  239. package/src/client/file-tree.ts +86 -0
  240. package/src/client/format.ts +37 -0
  241. package/src/client/glyphs.tsx +151 -0
  242. package/src/client/host-viewed.ts +195 -0
  243. package/src/client/index.ts +31 -0
  244. package/src/client/locales.ts +3446 -0
  245. package/src/client/menu-search.ts +16 -0
  246. package/src/client/mount.ts +439 -0
  247. package/src/client/review-queue.ts +256 -0
  248. package/src/client/review-threads.ts +204 -0
  249. package/src/client/review.ts +120 -0
  250. package/src/client/section-reach.ts +61 -0
  251. package/src/client/session-list.ts +79 -0
  252. package/src/client/source.ts +274 -0
  253. package/src/client/status.ts +171 -0
  254. package/src/client/thread-state.ts +127 -0
  255. package/src/client/toolbar-fold.ts +70 -0
  256. package/src/client/viewed-files.ts +178 -0
  257. package/src/client/worktree-settings-form.ts +43 -0
  258. package/src/commit-range.ts +27 -0
  259. package/src/css-modules.d.ts +5 -0
  260. package/src/diff.ts +162 -0
  261. package/src/git.ts +293 -0
  262. package/src/index.ts +1162 -0
  263. package/src/layers.ts +163 -0
  264. package/src/local-diff.ts +438 -0
  265. package/src/panel.ts +422 -0
  266. package/src/parse.ts +137 -0
  267. package/src/patch-cache.ts +73 -0
  268. package/src/review-cache.ts +98 -0
  269. package/src/states.ts +350 -0
  270. package/src/types.ts +504 -0
  271. package/src/wildmatch.ts +121 -0
  272. package/src/worktree.ts +576 -0
package/src/layers.ts ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Review layers of changed files. A repository's root `.gitattributes` decides first: its `dsh-review-layer`
3
+ * attribute names a layer, and `linguist-generated` places a file in the `test` layer. The panel's `testPaths` and
4
+ * `interfacePaths` configuration comes next, then the built-in rules, which follow the default file and directory
5
+ * conventions of common languages and tools; every other file is in the `implementation` layer.
6
+ */
7
+
8
+ import picomatch from 'picomatch'
9
+ import type { ParsedDiffFile } from './diff.ts'
10
+ import type { ForgeDiffFile, ForgeFileLayer } from './types.ts'
11
+ import { wildmatch } from './wildmatch.ts'
12
+
13
+ /** Path of the attributes file read beside each diff, relative to the repository root. */
14
+ export const ATTRIBUTES_PATH = '.gitattributes'
15
+
16
+ /** The attribute a repository sets to a layer name to place files in that layer. */
17
+ export const LAYER_ATTRIBUTE = 'dsh-review-layer'
18
+
19
+ /** The attribute GitHub Linguist reads to treat a file as generated. */
20
+ const GENERATED = 'linguist-generated'
21
+
22
+ const LAYERS: ReadonlySet<string> = new Set<ForgeFileLayer>(['interface', 'implementation', 'test'])
23
+
24
+ /** Whether an attribute value names a layer. */
25
+ function isLayer(value: string): value is ForgeFileLayer {
26
+ return LAYERS.has(value)
27
+ }
28
+
29
+ /**
30
+ * Tests, test data, snapshots, locale dictionaries, and lockfiles by the default conventions of their tools: test
31
+ * directories, Jest and Vitest `*.spec.*` and `*.test.*` files, `go test` `*_test.go` files and `testdata/`
32
+ * directories, pytest's `test_*.py`, `*_test.py`, and `conftest.py`, RSpec's `spec/` and `*_spec.rb`, SwiftPM's
33
+ * `Tests/`, .NET `*.Tests/` projects, Jest and insta snapshots, i18next and Rails `locales/`, gettext catalogs,
34
+ * Apple `.lproj` strings, Android string resources, and the lockfiles of npm, pnpm, Yarn, Bun, Cargo, Go modules,
35
+ * Poetry, uv, Pipenv, Bundler, Composer, SwiftPM, NuGet, Gradle, pub, Mix, and Nix flakes.
36
+ */
37
+ export const BUILT_IN_TEST_PATHS: readonly string[] = [
38
+ '**/test/**', '**/tests/**', '**/Tests/**', '**/__tests__/**', '**/spec/**', '**/e2e/**', '**/testdata/**', '**/__mocks__/**',
39
+ '**/__fixtures__/**', '**/*.Tests/**',
40
+ '**/*.spec.*', '**/*.test.*', '**/*.e2e.*', '**/*_test.go', '**/test_*.py', '**/*_test.py', '**/conftest.py', '**/*_spec.rb',
41
+ '**/__snapshots__/**', '**/*.snap',
42
+ '**/locales/**', '**/*.po', '**/*.pot', '**/*.lproj/*.strings', '**/res/values-*/strings.xml',
43
+ '**/package-lock.json', '**/npm-shrinkwrap.json', '**/pnpm-lock.yaml', '**/yarn.lock', '**/bun.lock', '**/bun.lockb', '**/Cargo.lock',
44
+ '**/go.sum', '**/poetry.lock', '**/uv.lock', '**/Pipfile.lock', '**/Gemfile.lock', '**/composer.lock', '**/Package.resolved',
45
+ '**/packages.lock.json', '**/gradle.lockfile', '**/pubspec.lock', '**/mix.lock', '**/flake.lock',
46
+ ]
47
+
48
+ /**
49
+ * Package manifests of npm, Go modules, Cargo, Python packaging, Bundler and RubyGems, Maven, Gradle, MSBuild,
50
+ * SwiftPM, Composer, pub, and Mix; TypeScript declarations, Python stubs, and C and C++ headers; and interface
51
+ * definitions of Protocol Buffers, GraphQL, Thrift, and OpenAPI.
52
+ */
53
+ export const BUILT_IN_INTERFACE_PATHS: readonly string[] = [
54
+ '**/package.json', '**/go.mod', '**/Cargo.toml', '**/pyproject.toml', '**/setup.py', '**/setup.cfg', '**/Gemfile', '**/*.gemspec',
55
+ '**/pom.xml', '**/build.gradle', '**/build.gradle.kts', '**/*.csproj', '**/Package.swift', '**/composer.json', '**/pubspec.yaml',
56
+ '**/mix.exs',
57
+ '**/*.d.ts', '**/*.d.mts', '**/*.d.cts', '**/*.pyi', '**/*.h', '**/*.hpp',
58
+ '**/*.proto', '**/*.graphql', '**/*.graphqls', '**/*.thrift', '**/openapi.{json,yaml,yml}', '**/swagger.{json,yaml,yml}',
59
+ ]
60
+
61
+ type Matcher = (path: string) => boolean
62
+
63
+ /** What a repository's attributes say about one path. */
64
+ interface PathAttributes {
65
+ /** The layer `dsh-review-layer` names, or undefined while it is unspecified. */
66
+ readonly layer: ForgeFileLayer | undefined
67
+ /** Whether `linguist-generated` is set. */
68
+ readonly generated: boolean
69
+ }
70
+
71
+ /**
72
+ * Compile globs into one matcher; `*` matches dot files and never crosses `/`.
73
+ * @param globs - picomatch globs.
74
+ * @returns whether a repository-relative path matches any glob.
75
+ */
76
+ function matcherOf(globs: readonly string[]): Matcher {
77
+ return globs.length === 0 ? () => false : picomatch([...globs], { dot: true })
78
+ }
79
+
80
+ /**
81
+ * Read the review attributes a `.gitattributes` text gives each path. Lines apply in order, so a later line overrides
82
+ * an earlier one. `dsh-review-layer=<layer>` names `test`, `interface`, or `implementation`; another value,
83
+ * `-dsh-review-layer`, and `!dsh-review-layer` leave the layer unspecified. `linguist-generated` and `=true` set
84
+ * the generated attribute, `-linguist-generated` and `=false` unset it, and `!linguist-generated` returns it to
85
+ * unspecified. Patterns follow Git's wildmatch rules, as {@link wildmatch} describes: a pattern without `/` matches a
86
+ * file name at any depth, and one with `/` matches the path from the repository root. Macro definitions, quoted
87
+ * patterns, negated patterns, which Git ignores in attributes, and patterns ending in `/`, which name directories and
88
+ * so never match a file, are skipped.
89
+ * @param attributes - the text of the root `.gitattributes`, empty without one.
90
+ * @returns the attributes of a repository-relative path.
91
+ */
92
+ export function attributesOf(attributes: string): (path: string) => PathAttributes {
93
+ // `undefined` leaves an attribute as earlier lines set it, and `null` returns it to unspecified.
94
+ const rules: {
95
+ readonly match: Matcher
96
+ readonly layer: ForgeFileLayer | null | undefined
97
+ readonly generated: boolean | null | undefined
98
+ }[] = []
99
+ for (const raw of attributes.split(/\r?\n/)) {
100
+ const [pattern, ...fields] = raw.trim().split(/\s+/)
101
+ if (pattern === undefined || pattern === '' || pattern.startsWith('#') || pattern.startsWith('[attr]')
102
+ || pattern.startsWith('"') || pattern.startsWith('!') || pattern.endsWith('/')) continue
103
+ let layer: ForgeFileLayer | null | undefined
104
+ let generated: boolean | null | undefined
105
+ for (const field of fields) {
106
+ if (field === GENERATED || field === `${GENERATED}=true`) generated = true
107
+ else if (field === `-${GENERATED}` || field === `${GENERATED}=false`) generated = false
108
+ else if (field === `!${GENERATED}`) generated = null
109
+ else if (field.startsWith(`${LAYER_ATTRIBUTE}=`)) {
110
+ const value = field.slice(LAYER_ATTRIBUTE.length + 1)
111
+ layer = isLayer(value) ? value : null
112
+ } else if (field === `-${LAYER_ATTRIBUTE}` || field === `!${LAYER_ATTRIBUTE}`) layer = null
113
+ }
114
+ const test = wildmatch(pattern.replace(/^\//, ''))
115
+ if (test === undefined || (layer === undefined && generated === undefined)) continue
116
+ const match: Matcher = pattern.includes('/') ? test : path => test(path.slice(path.lastIndexOf('/') + 1))
117
+ rules.push({ match, layer, generated })
118
+ }
119
+ return (path) => {
120
+ let layer: ForgeFileLayer | null | undefined
121
+ let generated: boolean | null | undefined
122
+ for (const rule of rules) {
123
+ if (!rule.match(path)) continue
124
+ if (rule.layer !== undefined) layer = rule.layer
125
+ if (rule.generated !== undefined) generated = rule.generated
126
+ }
127
+ return { layer: layer ?? undefined, generated: generated === true }
128
+ }
129
+ }
130
+
131
+ /** Classifies changed files into review layers by a repository's attributes, the panel's globs, and the built-in rules. */
132
+ export class FileLayers {
133
+ private readonly rules: readonly { readonly layer: ForgeFileLayer; readonly match: Matcher }[]
134
+
135
+ /**
136
+ * @param testPaths - configured globs of the `test` layer, checked before the built-in rules.
137
+ * @param interfacePaths - configured globs of the `interface` layer, checked after `testPaths` and before the built-in rules.
138
+ */
139
+ constructor(testPaths: readonly string[], interfacePaths: readonly string[]) {
140
+ this.rules = [
141
+ { layer: 'test', match: matcherOf(testPaths) },
142
+ { layer: 'interface', match: matcherOf(interfacePaths) },
143
+ { layer: 'test', match: matcherOf(BUILT_IN_TEST_PATHS) },
144
+ { layer: 'interface', match: matcherOf(BUILT_IN_INTERFACE_PATHS) },
145
+ ]
146
+ }
147
+
148
+ /**
149
+ * Place each file in its layer: the layer its attributes name, else `test` for a generated file, else the first
150
+ * configured or built-in rule its path matches, else `implementation`.
151
+ * @param files - parsed files.
152
+ * @param attributes - the text of the repository's root `.gitattributes`, empty without one.
153
+ * @returns the files in the same order with their layers.
154
+ */
155
+ classify(files: readonly ParsedDiffFile[], attributes: string): ForgeDiffFile[] {
156
+ const attributesAt = attributesOf(attributes)
157
+ return files.map((file) => {
158
+ const { layer, generated } = attributesAt(file.path)
159
+ const ruled = layer ?? (generated ? 'test' : this.rules.find(rule => rule.match(file.path))?.layer) ?? 'implementation'
160
+ return { ...file, layer: ruled }
161
+ })
162
+ }
163
+ }
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Local changes of a Session's checkout: where the `branch` scope forks, the
3
+ * patch of one scope with its untracked files, the new-side text of one file,
4
+ * and the size of the `branch` scope for the panel's card. Git runs through
5
+ * the Session's Git runner; untracked and working-tree files are read through
6
+ * `ctx.fs`, both within `maxDiffBytes`.
7
+ */
8
+
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import { FsError } from '@deepseek-ai/dsh-fs'
11
+ import type { Session } from '@deepseek-ai/dsh-session'
12
+ import { assertNever } from '@deepseek-ai/dsh-util-values'
13
+ import { rangeStart } from './commit-range.ts'
14
+ import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from './diff.ts'
15
+ import type { ParsedDiffFile } from './diff.ts'
16
+ import { gitIn, GitOutputTooLarge } from './git.ts'
17
+ import type { Git, GitConfig, GitOutput, Inspection } from './git.ts'
18
+ import { ATTRIBUTES_PATH } from './layers.ts'
19
+ import type { FileLayers } from './layers.ts'
20
+ import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts'
21
+ import type {
22
+ ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree,
23
+ } from './types.ts'
24
+ import type { ForgeCommit } from '@deepseek-ai/dsh-experimental-forge/types'
25
+
26
+ /** Git limits plus the size limits of local diffs. */
27
+ export interface DiffConfig extends GitConfig {
28
+ /** Largest patch, untracked file, or new-side file in bytes. */
29
+ readonly maxDiffBytes: number
30
+ /** Most untracked files listed. */
31
+ readonly maxUntrackedFiles: number
32
+ }
33
+
34
+ /** The commit the `branch` scope compares with and the name the panel shows for it. */
35
+ export interface ForkPoint {
36
+ /** Full commit object name. */
37
+ readonly commit: string
38
+ /** Branch such as `origin/master`, the created worktree's base branch, or an abbreviated commit. */
39
+ readonly label: string
40
+ /** Whether `commit` is the base commit of the worktree the Session created rather than a merge base. */
41
+ readonly worktree: boolean
42
+ }
43
+
44
+ /** Thrown when a patch, a file list, or a file exceeds `maxDiffBytes`. */
45
+ export class DiffTooLarge extends Error {
46
+ override name = 'DiffTooLarge'
47
+ }
48
+
49
+ /** Thrown when filter configuration cannot be read completely; no comparison has run. */
50
+ export class FilterConfigError extends Error {
51
+ override name = 'FilterConfigError'
52
+ }
53
+
54
+ /** Thrown for the `branch` scope of a checkout without a fork point. */
55
+ export class NoForkPoint extends Error {
56
+ override name = 'NoForkPoint'
57
+ }
58
+
59
+ /** Thrown when the base branch chosen for the `branch` scope does not exist. */
60
+ export class BaseMissing extends Error {
61
+ override name = 'BaseMissing'
62
+ }
63
+
64
+ /** Thrown when chosen commits are not among the commits of the `branch` scope, or are out of order. */
65
+ export class CommitsMissing extends Error {
66
+ override name = 'CommitsMissing'
67
+ }
68
+
69
+ /** Thrown when chosen commits of the `branch` scope are not a run in which each commit's first parent is the one before it. */
70
+ export class CommitsNotLinear extends Error {
71
+ override name = 'CommitsNotLinear'
72
+ }
73
+
74
+ /** A full SHA-1 or SHA-256 object name, the only form of a chosen commit Git receives. */
75
+ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
76
+
77
+ /** One commit per record: object name, first parent, author, author date, and subject, separated by NUL. */
78
+ const LOG_FORMAT = '--format=%H%x00%P%x00%an%x00%aI%x00%s%x1e'
79
+
80
+ /** No executable diff helpers or submodule working-tree inspection; preserve recorded submodule commit changes. */
81
+ const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv', '--submodule=short', '--ignore-submodules=dirty', '--no-color', '-M', '--src-prefix=a/', '--dst-prefix=b/'] as const
82
+
83
+ /** Disable enumerated clean/process filters for one diff without modifying Git configuration. */
84
+ async function diffFilterOverrides(git: Git): Promise<Readonly<Record<string, string>>> {
85
+ let configured: GitOutput
86
+ try {
87
+ configured = await git('filters', ['config', '--null', '--name-only', '--get-regexp', '^filter\\.'], [0, 1])
88
+ } catch (error) {
89
+ throw new FilterConfigError('Cannot read complete Git filter configuration; comparison was not run', { cause: error })
90
+ }
91
+ const overrides: Record<string, string> = {}
92
+ for (const key of configured.stdout.split('\0')) {
93
+ if (!key.endsWith('.clean') && !key.endsWith('.process')) continue
94
+ const driver = key.slice(0, key.lastIndexOf('.'))
95
+ overrides[`${driver}.clean`] = ''
96
+ overrides[`${driver}.process`] = ''
97
+ overrides[`${driver}.required`] = 'false'
98
+ }
99
+ return overrides
100
+ }
101
+
102
+ /** Characters Git inspects for a NUL character before it calls content binary. */
103
+ const BINARY_PROBE = 8000
104
+
105
+ /**
106
+ * Find where the `branch` scope forks while no base branch is chosen: the base commit of the worktree the
107
+ * Session created while the checkout is that worktree, else the merge base of
108
+ * HEAD with the default branch of the first remote that names one, in the
109
+ * order the panel recognizes code hosts.
110
+ * @param git - runner bound to the checkout.
111
+ * @param inspection - the checkout and its remotes.
112
+ * @param created - worktree the Session created, or null.
113
+ * @returns the fork point, or null when no remote names a default branch or HEAD shares no history with it.
114
+ */
115
+ export async function forkPoint(git: Git, inspection: Inspection, created: ForgeSessionWorktree | null): Promise<ForkPoint | null> {
116
+ if (created !== null && created.path === inspection.checkout.root) {
117
+ return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7), worktree: true }
118
+ }
119
+ for (const remote of remoteOrder(inspection.upstream, inspection.remotes)) {
120
+ const head = await git('remote-head', ['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote.name}/HEAD`], [0, 1, 128])
121
+ const base = head.exitCode === 0 ? parseName(head.stdout) : null
122
+ if (base === null) continue
123
+ const merge = await git('merge-base', ['merge-base', 'HEAD', base], [0, 1, 128])
124
+ const commit = merge.exitCode === 0 ? parseName(merge.stdout) : null
125
+ return commit === null ? null : { commit, label: base, worktree: false }
126
+ }
127
+ return null
128
+ }
129
+
130
+ /**
131
+ * Find where the `branch` scope forks from a chosen base branch: the merge base of HEAD with it.
132
+ * @param git - runner bound to the checkout.
133
+ * @param ref - full ref name under `refs/heads/` or `refs/remotes/`.
134
+ * @returns the fork point, or null when HEAD shares no history with the branch or has no commit.
135
+ * @throws BaseMissing when the ref does not exist; an Error for another ref name or when Git fails.
136
+ */
137
+ export async function chosenForkPoint(git: Git, ref: string): Promise<ForkPoint | null> {
138
+ const prefix = BASE_REF_PREFIXES.find(candidate => ref.startsWith(candidate) && ref.length > candidate.length)
139
+ if (prefix === undefined) throw new Error(`forge-panel: ${JSON.stringify(ref)} is not a branch ref`)
140
+ const name = ref.slice(prefix.length)
141
+ // `--verify` accepts only an exact ref path, so revision syntax such as `@{1}` never resolves.
142
+ const present = await git('show-ref', ['show-ref', '--verify', '--quiet', ref], [0, 1])
143
+ if (present.exitCode !== 0) throw new BaseMissing(`The base branch ${name} does not exist`)
144
+ const merge = await git('merge-base', ['merge-base', 'HEAD', ref], [0, 1, 128])
145
+ const commit = merge.exitCode === 0 ? parseName(merge.stdout) : null
146
+ return commit === null ? null : { commit, label: name, worktree: false }
147
+ }
148
+
149
+ /**
150
+ * List the branches the `branch` scope can compare with.
151
+ * @param git - runner bound to the checkout.
152
+ * @param inspection - the checkout and its remotes.
153
+ * @param created - worktree the Session created, or null.
154
+ * @param query - text the branch names must contain, ignoring case; empty for every branch.
155
+ * @param limit - most branches in each group.
156
+ * @returns the automatic fork point, then remote-tracking and local branches, most recently committed first.
157
+ * @throws an Error when Git fails or prints more than the runner's output limit.
158
+ */
159
+ export async function baseBranches(
160
+ git: Git,
161
+ inspection: Inspection,
162
+ created: ForgeSessionWorktree | null,
163
+ query: string,
164
+ limit: number,
165
+ ): Promise<ForgeBaseBranches> {
166
+ const fork = await forkPoint(git, inspection, created)
167
+ const refs = await git('base-branches', [
168
+ 'for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES,
169
+ ])
170
+ return {
171
+ automatic: fork === null ? null : { name: fork.label, worktree: fork.worktree },
172
+ ...parseBaseBranches(refs.stdout, inspection.checkout.branch, query, limit),
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Read changes at `root` with command-local clean/process filter overrides and without
178
+ * submodule working-tree inspection. Git's built-in newline, ident, and encoding conversions still apply.
179
+ * Each file's layer follows `layers` and the root `.gitattributes` of the new side: the index for `staged`,
180
+ * else the working tree.
181
+ * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`.
182
+ * @param config - Git and size limits.
183
+ * @param session - Session whose sandbox policy and execution world apply.
184
+ * @param root - top-level directory of the checkout.
185
+ * @param fork - fork point of the `branch` scope, or null without one.
186
+ * @param scope - which changes to read.
187
+ * @param layers - classifier of each file's review layer.
188
+ * @param signal - cancellation of every command and read.
189
+ * @returns tracked files in Git's order, then untracked files unless the scope is `staged`.
190
+ * @throws NoForkPoint for the `branch` scope without `fork`; FilterConfigError when filter configuration
191
+ * cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output or `.gitattributes`;
192
+ * an Error when Git or the `.gitattributes` read fails.
193
+ */
194
+ export async function localDiff(
195
+ ctx: Context,
196
+ config: DiffConfig,
197
+ session: Session,
198
+ root: string,
199
+ fork: ForkPoint | null,
200
+ scope: ForgeLocalScope,
201
+ layers: FileLayers,
202
+ signal: AbortSignal,
203
+ ): Promise<ForgeLocalDiff> {
204
+ const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal)
205
+ let range: readonly string[]
206
+ switch (scope.kind) {
207
+ case 'branch':
208
+ if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with')
209
+ if (scope.commits !== null) return await commitsDiff(git, fork, scope.commits, layers)
210
+ range = [fork.commit]
211
+ break
212
+ case 'uncommitted': range = [await headOrEmptyTree(git)]; break
213
+ case 'unstaged': range = []; break
214
+ case 'staged': range = ['--cached', await headOrEmptyTree(git)]; break
215
+ /* v8 ignore next -- closed ForgeLocalScope union exhaustiveness guard */
216
+ default: return assertNever(scope, 'ForgeLocalScope.kind')
217
+ }
218
+ const overrides = await diffFilterOverrides(git)
219
+ const tracked = parseDiff((await bounded(git('diff', [...DIFF, ...range, '--'], undefined, overrides))).stdout)
220
+ if (scope.kind === 'staged') {
221
+ const shown = await bounded(git('attributes', ['show', `:${ATTRIBUTES_PATH}`], [0, 128]))
222
+ return { base: null, files: layers.classify(tracked, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 }
223
+ }
224
+ const untracked = await untrackedFiles(ctx, config, git, root, signal)
225
+ let attributes = ''
226
+ try {
227
+ attributes = decodeText(await readFile(ctx, config, root, ATTRIBUTES_PATH, signal)) ?? ''
228
+ } catch (error) {
229
+ if (!(error instanceof FsError && error.code === 'FS_NOT_FOUND')) throw error
230
+ }
231
+ return {
232
+ base: fork === null || scope.kind !== 'branch' ? null : fork.label,
233
+ files: layers.classify([...tracked, ...untracked.files], attributes),
234
+ omitted: untracked.omitted,
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Read the new side of one file in a scope, which supplies the unchanged
240
+ * lines between hunks: the index for `staged`, the last chosen commit for
241
+ * chosen commits of the `branch` scope, else the working tree.
242
+ * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`.
243
+ * @param config - Git and size limits.
244
+ * @param session - Session whose sandbox policy and execution world apply.
245
+ * @param root - top-level directory of the checkout.
246
+ * @param scope - the scope whose new side to read.
247
+ * @param path - path relative to `root`, as the diff names it.
248
+ * @param signal - cancellation.
249
+ * @returns the text.
250
+ * @throws DiffTooLarge over `maxDiffBytes`; an Error for a path outside the checkout, binary content, or a failed read.
251
+ */
252
+ export async function localText(
253
+ ctx: Context,
254
+ config: DiffConfig,
255
+ session: Session,
256
+ root: string,
257
+ scope: ForgeLocalScope,
258
+ path: string,
259
+ signal: AbortSignal,
260
+ ): Promise<string> {
261
+ if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`)
262
+ let text: string | undefined
263
+ const commit = scope.kind === 'staged' ? '' : scope.kind === 'branch' && scope.commits !== null ? scope.commits.to : undefined
264
+ if (commit !== undefined) {
265
+ if (commit !== '' && !COMMIT.test(commit)) throw new CommitsMissing('The chosen commit is not a full object name')
266
+ const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal)
267
+ const shown = (await bounded(git('show', ['show', `${commit}:${path}`]))).stdout
268
+ text = shown.slice(0, BINARY_PROBE).includes('\0') ? undefined : shown
269
+ } else {
270
+ text = decodeText(await readFile(ctx, config, root, path, signal))
271
+ }
272
+ if (text === undefined) throw new Error(`forge-panel: ${path} is binary`)
273
+ return text
274
+ }
275
+
276
+ /**
277
+ * Measure the `branch` scope for the panel's card.
278
+ * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`.
279
+ * @param config - Git and size limits.
280
+ * @param session - Session whose sandbox policy and execution world apply.
281
+ * @param inspection - the checkout and its remotes.
282
+ * @param created - worktree the Session created, or null.
283
+ * @param signal - cancellation of every command and read.
284
+ * @returns the base and the changed files, or null without a fork point.
285
+ * @throws FilterConfigError when filter configuration cannot be read within `maxOutputBytes`;
286
+ * DiffTooLarge when the untracked file list exceeds `maxDiffBytes`; an Error when Git fails.
287
+ */
288
+ export async function localChanges(
289
+ ctx: Context,
290
+ config: DiffConfig,
291
+ session: Session,
292
+ inspection: Inspection,
293
+ created: ForgeSessionWorktree | null,
294
+ signal: AbortSignal,
295
+ ): Promise<ForgeLocalChanges | null> {
296
+ const root = inspection.checkout.root
297
+ const git = gitIn(ctx, config, session, root, signal)
298
+ const fork = await forkPoint(git, inspection, created)
299
+ if (fork === null) return null
300
+ const overrides = await diffFilterOverrides(git)
301
+ const numstat = await git('numstat', [...DIFF, '--numstat', '-z', fork.commit, '--'], undefined, overrides)
302
+ const listing = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal)
303
+ const untracked = await untrackedFiles(ctx, config, listing, root, signal)
304
+ return {
305
+ base: fork.label,
306
+ files: [
307
+ ...parseNumstat(numstat.stdout),
308
+ ...untracked.files.map(file => ({ path: file.path, additions: file.additions, deletions: 0, binary: file.binary })),
309
+ ],
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Count the commits the checkout has beyond a change request's head, which a
315
+ * change request diff does not show yet.
316
+ * @param git - runner bound to the Session's directory.
317
+ * @param branch - the change request's head branch.
318
+ * @param commit - the change request's head commit.
319
+ * @returns the count, or null on another branch, outside a checkout, or without the commit locally.
320
+ */
321
+ export async function aheadOf(git: Git, branch: string, commit: string): Promise<number | null> {
322
+ const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', '--short', 'HEAD'], [0, 1, 128])
323
+ if (head.exitCode !== 0 || parseName(head.stdout) !== branch) return null
324
+ const present = await git('cat-file', ['cat-file', '-e', `${commit}^{commit}`], [0, 1, 128])
325
+ if (present.exitCode !== 0) return null
326
+ return Number((await git('rev-list', ['rev-list', '--count', `${commit}..HEAD`])).stdout.trim())
327
+ }
328
+
329
+ /**
330
+ * List the commits of the `branch` scope: those reachable from HEAD but not from the fork point, parents before children.
331
+ * @param git - runner bound to the checkout, whose output limit bounds the listing.
332
+ * @param fork - fork point of the `branch` scope.
333
+ * @param limit - most commits listed.
334
+ * @returns the newest `limit` commits, ending with HEAD's commit, and HEAD's commit.
335
+ * @throws an Error when Git fails or prints more than the runner's output limit.
336
+ */
337
+ export async function localCommits(git: Git, fork: ForkPoint, limit: number): Promise<ForgeLocalCommits> {
338
+ const head = (await git('head', ['rev-parse', '--verify', 'HEAD'])).stdout.trim()
339
+ const listed = await branchCommits(git, fork, limit + 1)
340
+ return { headSha: head, commits: listed.slice(-limit), truncated: listed.length > limit }
341
+ }
342
+
343
+ /**
344
+ * Commits between the fork point and HEAD, parents before children.
345
+ * @param limit - when given, only the newest `limit` commits in topological order.
346
+ */
347
+ async function branchCommits(git: Git, fork: ForkPoint, limit?: number): Promise<ForgeCommit[]> {
348
+ // A configured `log.showSignature` would print verification text before the fields and run the verifying program.
349
+ const count = limit === undefined ? [] : [`--max-count=${String(limit)}`]
350
+ const output = await git('log', ['log', '--no-show-signature', '--topo-order', '--reverse', ...count, LOG_FORMAT, `${fork.commit}..HEAD`, '--'])
351
+ return output.stdout.split('\x1e').flatMap((record): ForgeCommit[] => {
352
+ const fields = record.replace(/^\n/, '').split('\0')
353
+ // The text after the last record holds no fields.
354
+ if (fields.length !== 5) return []
355
+ const [sha, parents, author, authoredAt, title] = fields as [string, string, string, string, string]
356
+ return [{ sha, parent: /^\S+/.exec(parents)?.[0] ?? null, title, author, authoredAt }]
357
+ })
358
+ }
359
+
360
+ /** The committed changes of consecutive commits of the `branch` scope, from the first commit's first parent to the last. */
361
+ async function commitsDiff(git: Git, fork: ForkPoint, chosen: ForgeCommitRange, layers: FileLayers): Promise<ForgeLocalDiff> {
362
+ if (!COMMIT.test(chosen.from) || !COMMIT.test(chosen.to)) throw new CommitsMissing('The chosen commits are not full object names')
363
+ const start = rangeStart(await branchCommits(git, fork), chosen)
364
+ if (start === 'missing') throw new CommitsMissing('The chosen commits are no longer on the branch')
365
+ if (start === 'not-linear') throw new CommitsNotLinear('The chosen commits are not one run of first parents')
366
+ // A first commit without a parent starts an unrelated history that HEAD merged; it adds every file.
367
+ const parent = start.parent ?? await emptyTree(git)
368
+ const overrides = await diffFilterOverrides(git)
369
+ const files = parseDiff((await bounded(git('diff', [...DIFF, parent, chosen.to, '--'], undefined, overrides))).stdout)
370
+ const shown = await bounded(git('attributes', ['show', `${chosen.to}:${ATTRIBUTES_PATH}`], [0, 128]))
371
+ return { base: fork.label, files: layers.classify(files, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 }
372
+ }
373
+
374
+ /** HEAD, or the empty tree while the checked-out branch has no commit. */
375
+ async function headOrEmptyTree(git: Git): Promise<string> {
376
+ const head = await git('head', ['rev-parse', '--verify', '--quiet', 'HEAD'], [0, 1])
377
+ return head.exitCode === 0 ? 'HEAD' : await emptyTree(git)
378
+ }
379
+
380
+ /** The object name of the empty tree. */
381
+ async function emptyTree(git: Git): Promise<string> {
382
+ return (await git('empty-tree', ['hash-object', '-t', 'tree', '--stdin'])).stdout.trim()
383
+ }
384
+
385
+ /** Untracked files Git does not ignore, at most `maxUntrackedFiles`; a nested repository and a file gone since the listing are left out. */
386
+ async function untrackedFiles(
387
+ ctx: Context,
388
+ config: DiffConfig,
389
+ git: Git,
390
+ root: string,
391
+ signal: AbortSignal,
392
+ ): Promise<{ readonly files: ParsedDiffFile[]; readonly omitted: number }> {
393
+ const listed = await bounded(git('untracked', ['ls-files', '--others', '--exclude-standard', '-z']))
394
+ const paths = listed.stdout.split('\0').filter(path => path.length > 0 && !path.endsWith('/'))
395
+ const files: ParsedDiffFile[] = []
396
+ for (const path of paths.slice(0, config.maxUntrackedFiles)) {
397
+ let content: Uint8Array
398
+ try {
399
+ content = await readFile(ctx, config, root, path, signal)
400
+ } catch (error) {
401
+ if (error instanceof DiffTooLarge) {
402
+ files.push(oversizedUntrackedFile(path))
403
+ continue
404
+ }
405
+ if (error instanceof FsError) continue
406
+ throw error
407
+ }
408
+ files.push(untrackedFile(path, content))
409
+ }
410
+ return { files, omitted: Math.max(0, paths.length - config.maxUntrackedFiles) }
411
+ }
412
+
413
+ /** Read one file of the checkout through `ctx.fs`, at most `maxDiffBytes`. */
414
+ async function readFile(ctx: Context, config: DiffConfig, root: string, path: string, signal: AbortSignal): Promise<Uint8Array> {
415
+ const target = await ctx.fs.resolve(path, { cwd: root, signal })
416
+ try {
417
+ return await ctx.fs.readBytes(target, signal, config.maxDiffBytes)
418
+ } catch (error) {
419
+ if (error instanceof FsError && error.code === 'FS_TOO_LARGE') throw new DiffTooLarge(`${path} exceeds maxDiffBytes`, { cause: error })
420
+ throw error
421
+ }
422
+ }
423
+
424
+ /** Translate the runner's output limit into DiffTooLarge. */
425
+ async function bounded(output: Promise<GitOutput>): Promise<GitOutput> {
426
+ try {
427
+ return await output
428
+ } catch (error) {
429
+ if (error instanceof GitOutputTooLarge) throw new DiffTooLarge(error.message, { cause: error })
430
+ throw error
431
+ }
432
+ }
433
+
434
+ /** Whether a diff path stays inside the checkout: relative, without NUL, and without a `..` segment. */
435
+ function insideCheckout(path: string): boolean {
436
+ if (path.length === 0 || path.includes('\0') || path.startsWith('/') || /^[A-Za-z]:/.test(path)) return false
437
+ return path.split(/[/\\]/).every(segment => segment !== '..')
438
+ }