@young1lin/dsh-ui-gitworkbench 0.1.14 → 0.1.16

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 (43) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/CHANGELOG_EN.md +23 -0
  3. package/README.md +29 -3
  4. package/README_EN.md +1 -1
  5. package/lib/client.js +1512 -470
  6. package/lib/dir-listing.js +34 -0
  7. package/lib/fs-remove.js +5 -36
  8. package/lib/index.js +346 -117
  9. package/lib/path-lock.js +54 -0
  10. package/lib/repo-root.js +60 -0
  11. package/lib/worktree.js +83 -0
  12. package/lib/write-checked.js +1 -1
  13. package/package.json +5 -5
  14. package/src/client/ChromeGlyph.tsx +5 -0
  15. package/src/client/CodeEditor.tsx +19 -1
  16. package/src/client/DiffViews.tsx +116 -121
  17. package/src/client/FileBrowser.tsx +196 -23
  18. package/src/client/GitWorkbenchPanel.module.css +1 -0
  19. package/src/client/GitWorkbenchPanel.tsx +100 -12
  20. package/src/client/SideRails.tsx +106 -0
  21. package/src/client/diff-cells.tsx +147 -0
  22. package/src/client/diff-nav.ts +4 -1
  23. package/src/client/dir-tree.ts +31 -1
  24. package/src/client/file-rows.ts +40 -0
  25. package/src/client/h-rail.ts +70 -0
  26. package/src/client/ignored-cache.ts +193 -0
  27. package/src/client/index.ts +22 -3
  28. package/src/client/locales.ts +12 -2
  29. package/src/client/row-heights.ts +225 -0
  30. package/src/client/styles/changes.css +33 -2
  31. package/src/client/styles/controls.css +5 -0
  32. package/src/client/styles/files.css +5 -0
  33. package/src/client/styles/rails.css +72 -0
  34. package/src/client/use-row-window.ts +7 -3
  35. package/src/client/use-variable-row-window.ts +210 -0
  36. package/src/dir-listing.ts +47 -0
  37. package/src/fs-remove.ts +5 -36
  38. package/src/index.ts +372 -118
  39. package/src/path-lock.ts +56 -0
  40. package/src/repo-root.ts +66 -0
  41. package/src/types/dsh-shim.d.ts +12 -2
  42. package/src/worktree.ts +97 -0
  43. package/src/write-checked.ts +1 -1
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The one place a client-supplied path becomes an absolute path on disk.
3
+ *
4
+ * git needs no such lock: whatever pathspec it is handed, it will not read or
5
+ * write outside the repository, which is why `isSafePathArg` only has to keep
6
+ * a path from being mistaken for an option. The moment a path leaves git and
7
+ * reaches `readFile`, `stat` or `readdir`, that backstop is gone — `join(root,
8
+ * '../../../etc/passwd')` is just a path, and the browser is the least trusted
9
+ * source of paths this plugin has.
10
+ *
11
+ * So every filesystem call in the host resolves through here, and the RPCs
12
+ * that do it are pinned by `host-rooted-paths.test.ts` so a new one cannot
13
+ * quietly join a client string onto the root instead.
14
+ *
15
+ * What this does NOT defend against, deliberately and for the same reason
16
+ * `fs-remove.ts` says so: `resolve` is lexical, so a SYMLINK inside the
17
+ * worktree that points outward still resolves inside and is followed. Closing
18
+ * that means a `realpath` per segment on every read of every file, for a case
19
+ * git itself does not defend against and that presupposes write access to the
20
+ * repository the reader already opened.
21
+ *
22
+ * @module @young1lin/dsh-ui-gitworkbench/path-lock
23
+ */
24
+
25
+ import { resolve, sep } from 'node:path'
26
+
27
+ import { isSafeRelativePath } from './discard-ops.js'
28
+
29
+ /**
30
+ * Resolve a repo-relative path against the worktree root, refusing to leave it.
31
+ *
32
+ * Two locks, not one. {@link isSafeRelativePath} rejects the traversal
33
+ * SPELLINGS — absolute paths, drive letters, UNC prefixes, NUL bytes, any `..`
34
+ * segment including one buried mid-path. The `startsWith` below re-checks the
35
+ * RESOLVED path, which is the form the filesystem acts on, so a path that
36
+ * survives the first check by being spelled unusually still has to land inside
37
+ * the root to be acted on.
38
+ *
39
+ * @param root - the worktree directory, absolute.
40
+ * @param relative - repo-relative path from the client or from git's output.
41
+ * @returns the absolute path to act on.
42
+ * @throws if the path is not a safe relative path, resolves outside the root,
43
+ * or IS the root.
44
+ */
45
+ export function resolveInside(root: string, relative: string): string {
46
+ if (!isSafeRelativePath(relative)) {
47
+ throw new Error(`unsafe path argument: ${JSON.stringify(relative)}`)
48
+ }
49
+ const base = resolve(root)
50
+ const target = resolve(base, relative)
51
+ if (target === base) throw new Error('refusing to act on the worktree root itself')
52
+ if (!target.startsWith(base + sep)) {
53
+ throw new Error(`path escapes the worktree: ${JSON.stringify(relative)}`)
54
+ }
55
+ return target
56
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Where the drawer runs git: at the repository ROOT, not at the directory the
3
+ * session happened to open.
4
+ *
5
+ * Every path the drawer carries — the tree's entries, the diff's pathspecs,
6
+ * the editor's save target — is REPOSITORY-RELATIVE, because that is what
7
+ * `git status --porcelain` and `git diff --numstat` print wherever they run.
8
+ * Pathspecs and `:path` revisions are the opposite: git resolves them against
9
+ * the process cwd. The two coincide only when the session opened the root
10
+ * itself. A session opened at a subdirectory (a monorepo's `server/`, say)
11
+ * gets a drawer that LISTS the right files and then quietly fails to do
12
+ * anything with them: `git diff HEAD -- server/main.go` run from `server/`
13
+ * looks for `server/server/main.go`, matches nothing, and exits 0 with empty
14
+ * output — a changed file that opens to a blank pane, a stage tick that dies
15
+ * with "pathspec did not match", a blame that cannot find the path in HEAD.
16
+ *
17
+ * Resolving the root once and running everything there makes every
18
+ * repository-relative spelling correct by construction, whatever directory the
19
+ * session opened. The resolve is a real git spawn per RPC entry — folded into
20
+ * the parallel batch where a poll pays for it — and deliberately NOT cached:
21
+ * re-resolving per call is what lets `git init` run inside a subdirectory
22
+ * mid-session and be picked up by the next poll, and a cache would trade that
23
+ * for a spawn that already runs concurrently with the reads it precedes.
24
+ *
25
+ * Pure and git-injected (the `write-checked` pattern) so vitest can pin both
26
+ * halves: the resolution itself, and the git behaviors the whole arrangement
27
+ * rests on.
28
+ *
29
+ * @module @young1lin/dsh-ui-gitworkbench/repo-root
30
+ */
31
+
32
+ import type { GitRun } from './apply-blocks.js'
33
+
34
+ /** Run git in `cwd`. Must not throw — report through `exitCode`/`stderr`. */
35
+ export type RootGit = (cwd: string, argv: readonly string[]) => Promise<GitRun>
36
+
37
+ /**
38
+ * The repository root of a directory, or null when git knows none.
39
+ *
40
+ * `--show-toplevel` is the discovery git itself uses, so what it returns is by
41
+ * definition where the porcelain paths of commands run in that directory are
42
+ * rooted — including a linked worktree's own root when the directory sits in
43
+ * one. Output is normalized to forward slashes so `join()` behaves the same on
44
+ * every platform (git for Windows already prints them that way).
45
+ * @param git - how to run git.
46
+ * @param cwd - any directory inside the repository.
47
+ */
48
+ export async function resolveRepoRoot(git: RootGit, cwd: string): Promise<string | null> {
49
+ const out = await git(cwd, ['rev-parse', '--show-toplevel'])
50
+ if (out.exitCode !== 0) return null
51
+ return out.stdout.trim().replace(/\\/g, '/') || null
52
+ }
53
+
54
+ /**
55
+ * The directory to run git in for a session's workspace: its repository root,
56
+ * or the directory itself when it is not inside a repository.
57
+ *
58
+ * The fallback keeps the failure honest: outside a repository the caller's own
59
+ * git run fails exactly as it did before this module existed, and that error —
60
+ * not a resolution error — is what the reader should see.
61
+ * @param git - how to run git.
62
+ * @param cwd - the directory the session opened.
63
+ */
64
+ export async function rootedDir(git: RootGit, cwd: string): Promise<string> {
65
+ return (await resolveRepoRoot(git, cwd)) ?? cwd
66
+ }
@@ -12,17 +12,27 @@ declare module '@deepseek-ai/cordis' {
12
12
  /** ToolRuntime.register — returns the dispose callback; loose here, see file header. */
13
13
  register(definition: unknown): () => void
14
14
  }
15
+ /**
16
+ * Event bus, mixed onto ctx in real cordis. Only `on` is mirrored, loose:
17
+ * the typed event table lives in the @deepseek-ai/dsh-* packages this shim
18
+ * stands in for. Listeners are fiber-owned and removed on unload.
19
+ */
20
+ events: {
21
+ on(name: string, listener: (...args: any[]) => void): void
22
+ }
15
23
  /**
16
24
  * SystemPrompt registry. Only `context()` is mirrored — the dynamic
17
25
  * per-assembly contribution, whose `text` provider is SYNCHRONOUS (see the
18
26
  * real `PromptContext` in packages/core/system-prompt/src/index.ts). The
19
- * `agent` field on the assemble context is merged in by `dsh-agent`.
27
+ * `agent` field on the assemble context is merged in by `dsh-agent`; its
28
+ * session header carries the parent edge a subagent is born with
29
+ * (`SessionHeader.parentSession` in packages/core/session).
20
30
  */
21
31
  systemPrompt: {
22
32
  context(input: {
23
33
  name: string
24
34
  order: number
25
- text: (context: { agent?: { session: { id: string } } }) => string
35
+ text: (context: { agent?: { session: { id: string; header?: { parentSession?: string } } } }) => string
26
36
  }): () => void
27
37
  }
28
38
  /** Mount a child scope once the named services are available; loose here, see file header. */
package/src/worktree.ts CHANGED
@@ -187,6 +187,103 @@ export function worktreeDir(repoRoot: string, name: string): string {
187
187
  return `${repoRoot.replace(/\/+$/, '')}/.agents/worktrees/${name}`
188
188
  }
189
189
 
190
+ // ---- session lineage: the binding a session effectively works under ----
191
+
192
+ /** A binding resolved for a session, with whether it is the session's own. */
193
+ export interface EffectiveBinding<T> {
194
+ readonly binding: T
195
+ /** False when the binding is the session's own; true when an ancestor's. */
196
+ readonly inherited: boolean
197
+ }
198
+
199
+ /**
200
+ * Deepest ancestor chain walked before the lookup gives up. Real delegation
201
+ * nests two or three levels; the cap exists so a corrupt lineage (a cycle the
202
+ * guard below somehow missed, a pathologically deep chain) costs a bounded
203
+ * number of lookups instead of walking forever.
204
+ */
205
+ const LINEAGE_HOP_CAP = 8
206
+
207
+ /**
208
+ * Resolve the binding a session effectively works under: its own, else the
209
+ * nearest ancestor's.
210
+ *
211
+ * A subagent session never gets a binding of its own — `worktree_enter` is
212
+ * called by the session that wants the worktree — but it works wherever its
213
+ * parent conversation works: the standing prompt, the chip, and `worktree_exit`'s
214
+ * diagnostics all answer "which worktree is THIS session in" through here. The
215
+ * walk is re-resolved on every read, so a session exiting its worktree changes
216
+ * only its own binding: descendants lend the next bound ancestor up the chain
217
+ * on their next read (possibly none — the common case — possibly a grandparent's,
218
+ * which is still the conversation tree they work in) and nothing dangles.
219
+ *
220
+ * Own wins over inherited on purpose: a session that enters a worktree of its
221
+ * own is deliberately somewhere else than its parent.
222
+ * @param sessionId - the session whose effective binding is wanted.
223
+ * @param parentOf - session id → parent session id, as `agent/session-start`
224
+ * delivered it (subagent headers name their parent).
225
+ * @param bindingOf - binding lookup (the bindings file, or the prompt mirror).
226
+ * @returns the effective binding, or undefined when neither the session nor any
227
+ * ancestor (within the hop cap) is bound.
228
+ */
229
+ export function resolveEffectiveBinding<T>(
230
+ sessionId: string,
231
+ parentOf: ReadonlyMap<string, string>,
232
+ bindingOf: (id: string) => T | undefined,
233
+ ): EffectiveBinding<T> | undefined {
234
+ const own = bindingOf(sessionId)
235
+ if (own !== undefined) return { binding: own, inherited: false }
236
+ const seen = new Set<string>([sessionId])
237
+ let ancestor = parentOf.get(sessionId)
238
+ for (let hops = 0; ancestor !== undefined && hops < LINEAGE_HOP_CAP; hops += 1) {
239
+ if (seen.has(ancestor)) return undefined
240
+ seen.add(ancestor)
241
+ const binding = bindingOf(ancestor)
242
+ if (binding !== undefined) return { binding, inherited: true }
243
+ ancestor = parentOf.get(ancestor)
244
+ }
245
+ return undefined
246
+ }
247
+
248
+ /**
249
+ * The session's parent edge, read off a dsh session header: the id of the
250
+ * session this one was delegated by, or undefined for a top-level session (or
251
+ * a malformed empty value). Both `parentOf` feeds — the `agent/session-start`
252
+ * listener and the prompt-time self-heal — go through here, so their input
253
+ * guards cannot drift apart.
254
+ */
255
+ export function lineageEdgeOf(header: { readonly parentSession?: string } | undefined): string | undefined {
256
+ const parent = header?.parentSession
257
+ return typeof parent === 'string' && parent.length > 0 ? parent : undefined
258
+ }
259
+
260
+ /**
261
+ * The standing notice for a session's effective binding — the text the
262
+ * `worktree:binding` prompt context returns. Both variants carry the same two
263
+ * operational rules; what differs is who holds the binding, and the inherited
264
+ * variant must NOT offer `worktree_exit` (the caller cannot unbind a parent's
265
+ * binding — the exit would fail, and the model should not be told to try).
266
+ * @param name - worktree name (also the directory under `.agents/worktrees/`).
267
+ * @param branch - branch checked out there, when known.
268
+ * @param inherited - whether an ancestor, not this session, holds the binding.
269
+ */
270
+ export function bindingNotice(name: string, branch: string | undefined, inherited: boolean): string {
271
+ const rel = `.agents/worktrees/${name}`
272
+ const branchNote = branch === undefined ? '' : ` (branch ${branch})`
273
+ const opening = inherited
274
+ ? `This session works in git worktree "${name}"${branchNote}, entered by its parent session.`
275
+ : `This session is bound to git worktree "${name}"${branchNote}.`
276
+ const closing = inherited
277
+ ? 'A path without that prefix acts on the MAIN worktree, not the worktree this conversation works in. '
278
+ + '(The binding belongs to the parent session; worktree_exit here would not unbind it.)'
279
+ : 'A path without that prefix acts on the MAIN worktree, not the bound one. Call worktree_exit to unbind.'
280
+ return `${opening}\n`
281
+ + 'The session working directory is still the repository root, so the binding is a convention you must apply yourself:\n'
282
+ + `- shell commands: pass workdir "${rel}"\n`
283
+ + `- file tools: prefix every path with ${rel}/\n`
284
+ + closing
285
+ }
286
+
190
287
  export function parseWorktreeList(porcelain: string): WorktreeEntry[] {
191
288
  const out: WorktreeEntry[] = []
192
289
  let path = ''
@@ -33,7 +33,7 @@
33
33
  import { randomBytes } from 'node:crypto'
34
34
 
35
35
  import { renameWithRetry } from './atomic-json.js'
36
- import { resolveInside } from './fs-remove.js'
36
+ import { resolveInside } from './path-lock.js'
37
37
  import { decodesAsUtf8, isSafePathArg, type OpFailure } from './git-ops.js'
38
38
  import type { GitRun } from './apply-blocks.js'
39
39