@linxin666/dsh-client-ui-task-board-ssh 0.0.0-stage → 0.4.20

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 (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +85 -2
  4. package/README.zh.md +86 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4429 -0
  8. package/lib/index.js +6100 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +100 -0
  13. package/lib/types/client/locales.d.ts +125 -0
  14. package/lib/types/client/seat-props.d.ts +53 -0
  15. package/lib/types/client/settings-entry-form.d.ts +49 -0
  16. package/lib/types/client/settings-form.d.ts +237 -0
  17. package/lib/types/client/ssh/card-decoration.d.ts +23 -0
  18. package/lib/types/client/ssh/compose-section.d.ts +7 -0
  19. package/lib/types/client/ssh/detail-section.d.ts +7 -0
  20. package/lib/types/client/ssh/extension.d.ts +54 -0
  21. package/lib/types/client/ssh/log-buffer.d.ts +128 -0
  22. package/lib/types/client/ssh/log-view.d.ts +37 -0
  23. package/lib/types/client/ssh/model.d.ts +130 -0
  24. package/lib/types/client/ssh/settings-section.d.ts +134 -0
  25. package/lib/types/client/ssh/summary.d.ts +160 -0
  26. package/lib/types/client/ssh/target-form.d.ts +60 -0
  27. package/lib/types/core/action.d.ts +89 -0
  28. package/lib/types/core/adapters/claude.d.ts +15 -0
  29. package/lib/types/core/adapters/codex.d.ts +15 -0
  30. package/lib/types/core/adapters/custom.d.ts +29 -0
  31. package/lib/types/core/adapters/dsh.d.ts +21 -0
  32. package/lib/types/core/adapters/index.d.ts +25 -0
  33. package/lib/types/core/adapters/types.d.ts +76 -0
  34. package/lib/types/core/contract.d.ts +445 -0
  35. package/lib/types/core/launcher-script.d.ts +13 -0
  36. package/lib/types/core/launcher.d.ts +153 -0
  37. package/lib/types/core/ledger.d.ts +123 -0
  38. package/lib/types/core/shell.d.ts +61 -0
  39. package/lib/types/core/target.d.ts +143 -0
  40. package/lib/types/core/task-record.d.ts +63 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +71 -0
  43. package/lib/types/host/engine.d.ts +418 -0
  44. package/lib/types/host/extension.d.ts +59 -0
  45. package/lib/types/host/logs.d.ts +135 -0
  46. package/lib/types/host/payload.d.ts +75 -0
  47. package/lib/types/host/prompt.d.ts +44 -0
  48. package/lib/types/host/queue.d.ts +53 -0
  49. package/lib/types/host/remote.d.ts +120 -0
  50. package/lib/types/host/settings.d.ts +149 -0
  51. package/lib/types/host/timers.d.ts +20 -0
  52. package/lib/types/host/tools.d.ts +15 -0
  53. package/lib/types/host/workspace/errors.d.ts +29 -0
  54. package/lib/types/host/workspace/git.d.ts +108 -0
  55. package/lib/types/host/workspace/in-place.d.ts +36 -0
  56. package/lib/types/host/workspace/index.d.ts +28 -0
  57. package/lib/types/host/workspace/layout.d.ts +62 -0
  58. package/lib/types/host/workspace/local-git.d.ts +72 -0
  59. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  60. package/lib/types/host/workspace/remote.d.ts +85 -0
  61. package/lib/types/host/workspace/types.d.ts +28 -0
  62. package/lib/types/host/workspace-seam.d.ts +100 -0
  63. package/lib/types/index.d.ts +97 -0
  64. package/lib/types/mount-once.d.ts +55 -0
  65. package/locale/en.json +6 -0
  66. package/locale/zh.json +6 -0
  67. package/package.json +89 -3
  68. package/src/client/PluginSettingsCard.tsx +838 -0
  69. package/src/client/RangeBubble.tsx +164 -0
  70. package/src/client/SegmentGroup.tsx +93 -0
  71. package/src/client/css-modules.d.ts +5 -0
  72. package/src/client/index.ts +195 -0
  73. package/src/client/locales.ts +257 -0
  74. package/src/client/seat-props.ts +58 -0
  75. package/src/client/settings-card.module.css +821 -0
  76. package/src/client/settings-entry-form.ts +141 -0
  77. package/src/client/settings-form.ts +529 -0
  78. package/src/client/ssh/card-decoration.tsx +55 -0
  79. package/src/client/ssh/compose-section.tsx +147 -0
  80. package/src/client/ssh/detail-section.tsx +345 -0
  81. package/src/client/ssh/extension.ts +271 -0
  82. package/src/client/ssh/log-buffer.ts +224 -0
  83. package/src/client/ssh/log-view.tsx +149 -0
  84. package/src/client/ssh/model.ts +299 -0
  85. package/src/client/ssh/settings-section.tsx +401 -0
  86. package/src/client/ssh/summary.ts +388 -0
  87. package/src/client/ssh/target-form.tsx +380 -0
  88. package/src/client/ssh.module.css +617 -0
  89. package/src/core/action.ts +270 -0
  90. package/src/core/adapters/claude.ts +64 -0
  91. package/src/core/adapters/codex.ts +83 -0
  92. package/src/core/adapters/custom.ts +88 -0
  93. package/src/core/adapters/dsh.ts +87 -0
  94. package/src/core/adapters/index.ts +74 -0
  95. package/src/core/adapters/types.ts +95 -0
  96. package/src/core/contract.ts +510 -0
  97. package/src/core/launcher-script.ts +313 -0
  98. package/src/core/launcher.ts +283 -0
  99. package/src/core/ledger.ts +372 -0
  100. package/src/core/shell.ts +77 -0
  101. package/src/core/target.ts +413 -0
  102. package/src/core/task-record.ts +65 -0
  103. package/src/core/workspace.ts +78 -0
  104. package/src/host/board.ts +103 -0
  105. package/src/host/engine.ts +1602 -0
  106. package/src/host/extension.ts +304 -0
  107. package/src/host/logs.ts +297 -0
  108. package/src/host/payload.ts +134 -0
  109. package/src/host/prompt.ts +89 -0
  110. package/src/host/queue.ts +73 -0
  111. package/src/host/remote.ts +328 -0
  112. package/src/host/settings.ts +294 -0
  113. package/src/host/timers.ts +33 -0
  114. package/src/host/tools.ts +259 -0
  115. package/src/host/workspace/errors.ts +43 -0
  116. package/src/host/workspace/git.ts +305 -0
  117. package/src/host/workspace/in-place.ts +58 -0
  118. package/src/host/workspace/index.ts +37 -0
  119. package/src/host/workspace/layout.ts +122 -0
  120. package/src/host/workspace/local-git.ts +164 -0
  121. package/src/host/workspace/remote-git.ts +244 -0
  122. package/src/host/workspace/remote.ts +181 -0
  123. package/src/host/workspace/types.ts +34 -0
  124. package/src/host/workspace-seam.ts +132 -0
  125. package/src/index.ts +243 -0
  126. package/src/mount-once.ts +142 -0
@@ -0,0 +1,305 @@
1
+ /**
2
+ * The per-run git worktree, and the two places its repository comes from.
3
+ *
4
+ * One mechanism covers both user modes: a bare cache on the host holds the
5
+ * objects, each run gets its own worktree on branch `dsh-task/<runId>`, a ref
6
+ * pins the commit that branch started from, and `collect` publishes whatever
7
+ * the run added on top. A url source fetches the branches from a repository the
8
+ * host can reach and pushes the run's branch back to it; a workspace source
9
+ * receives the local repository as a bundle and brings the branch back the same
10
+ * way, through `dshSsh` rather than through system `ssh`, so the run uses the
11
+ * credentials and jump hosts the user already configured.
12
+ *
13
+ * Every step is derived from the run, so `prepare` is idempotent on `runId` and
14
+ * `collect` can run in a later process — after the local host was offline — and
15
+ * still find the worktree, the branch and the base commit it left behind.
16
+ *
17
+ * @module dsh-task-board-ssh/host/workspace/git
18
+ */
19
+ import { mkdtemp, rm } from 'node:fs/promises'
20
+ import { tmpdir } from 'node:os'
21
+ import { join } from 'node:path'
22
+ import { shellEnsureDir } from '../../core/shell.ts'
23
+ import type { SshGitSource } from '../../core/target.ts'
24
+ import type { SshWorkspaceCollection, SshWorkspaceRun } from '../../core/workspace.ts'
25
+ import { SshWorkspaceError, boundedLine } from './errors.ts'
26
+ import { gitWorkspaceLayout, type GitWorkspaceLayout } from './layout.ts'
27
+ import { countUntrackedFiles, createWorkspaceBundle, fetchRunBranch } from './local-git.ts'
28
+ import {
29
+ addWorktreeCommand,
30
+ attachWorktreeCommand,
31
+ branchProbeCommand,
32
+ bundleResultCommand,
33
+ countRunCommitsCommand,
34
+ fetchBundleCommand,
35
+ fetchUrlCommand,
36
+ pinBaseCommand,
37
+ prepareCacheCommand,
38
+ preparedProbeCommand,
39
+ pushBranchCommand,
40
+ remoteStartRef,
41
+ removeWorktreeCommand,
42
+ } from './remote-git.ts'
43
+ import {
44
+ downloadFromHost,
45
+ execRemote,
46
+ execRemoteChecked,
47
+ probeRemote,
48
+ redactGitUrl,
49
+ removeRemoteFile,
50
+ uploadToHost,
51
+ } from './remote.ts'
52
+ import type { SshWorkspacePreparationNote, SshWorkspaceStrategyWithNote } from './types.ts'
53
+
54
+ /** A repository the host reaches by URL. */
55
+ type UrlSource = Extract<SshGitSource, { kind: 'url' }>
56
+
57
+ /** The local workspace repository, sent as a bundle. */
58
+ type WorkspaceSource = Extract<SshGitSource, { kind: 'workspace' }>
59
+
60
+ /** Prefix of every local scratch directory, so a leaked one is attributable. */
61
+ const SCRATCH_PREFIX = 'dsh-task-board-ssh-'
62
+
63
+ /**
64
+ * Per-(host, bare cache) serialization tails so concurrent runs against the
65
+ * same repository (e.g. default perHostCap = 2) never collide on `git init`,
66
+ * `worktree prune`, or shared `refs/dsh-remote/*` ref locks.
67
+ */
68
+ const cacheQueues = new Map<string, Promise<unknown>>()
69
+
70
+ async function withCacheLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
71
+ const prev = cacheQueues.get(key) ?? Promise.resolve()
72
+ const run = prev.catch(() => {}).then(fn)
73
+ const tail = run.then(() => {}, () => {})
74
+ cacheQueues.set(key, tail)
75
+ try {
76
+ return await run
77
+ } finally {
78
+ if (cacheQueues.get(key) === tail) cacheQueues.delete(key)
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The git mechanism's shared state machine.
84
+ *
85
+ * A subclass only answers where the cache's start commit comes from and where
86
+ * `collect` publishes the branch; the cache, the worktree, the base ref and the
87
+ * "did the run commit anything" question are the same for both sources.
88
+ */
89
+ abstract class GitWorkspaceStrategyBase implements SshWorkspaceStrategyWithNote {
90
+ readonly kind = 'git' as const
91
+
92
+ /** What makes this repository source unique on one host. */
93
+ private readonly sourceIdentity: string
94
+
95
+ /**
96
+ * @param sourceIdentity - cache key identity of the pinned source.
97
+ */
98
+ protected constructor(sourceIdentity: string) {
99
+ this.sourceIdentity = sourceIdentity
100
+ }
101
+
102
+ /** Effective run whose worktree/branch this operation owns (reused on follow-up/rework). */
103
+ private layoutFor(run: SshWorkspaceRun): GitWorkspaceLayout {
104
+ const effectiveRunId = run.reuseWorktreeRunId ?? run.runId
105
+ return gitWorkspaceLayout({ ...run, runId: effectiveRunId }, this.sourceIdentity)
106
+ }
107
+
108
+ /**
109
+ * Make the run's worktree exist on its branch, or confirm it already does.
110
+ * @param run - the run being prepared.
111
+ * @returns the worktree path, plus the source's note when it has one.
112
+ * @throws SshWorkspaceError when the host, the source or git refused.
113
+ */
114
+ async prepare(run: SshWorkspaceRun): Promise<SshWorkspacePreparationNote> {
115
+ const layout = this.layoutFor(run)
116
+ const note = await this.sourceNote(run)
117
+ const lockKey = `${run.host}:${layout.cacheDir}`
118
+ return await withCacheLock(lockKey, async () => {
119
+ if (await probeRemote(run, preparedProbeCommand(layout))) return { cwd: layout.worktreeDir, ...note }
120
+ await execRemoteChecked(run, prepareCacheCommand(layout), 'preparing the repository cache')
121
+ if (await probeRemote(run, branchProbeCommand(layout))) {
122
+ // The branch outlived its directory; re-attach it instead of resetting it,
123
+ // because the commits it carries are the run's work.
124
+ await execRemoteChecked(run, attachWorktreeCommand(layout), `re-attaching the worktree of ${layout.branch}`)
125
+ } else {
126
+ const start = await this.seed(run, layout)
127
+ await execRemoteChecked(run, addWorktreeCommand(layout, start), `creating the worktree of ${layout.branch}`)
128
+ }
129
+ return { cwd: layout.worktreeDir, ...note }
130
+ })
131
+ }
132
+
133
+ /**
134
+ * Bring the run's branch back, when the run committed anything.
135
+ * @param run - the settled run.
136
+ * @returns the branch that carries the result, or nothing when there is none.
137
+ * @throws SshWorkspaceError when no workspace was prepared or publishing failed.
138
+ */
139
+ async collect(run: SshWorkspaceRun): Promise<SshWorkspaceCollection> {
140
+ const layout = this.layoutFor(run)
141
+ if (!(await probeRemote(run, branchProbeCommand(layout)))) {
142
+ throw new SshWorkspaceError(`this run has no prepared git workspace on ${run.host}: ${layout.branch}`)
143
+ }
144
+ if ((await this.countRunCommits(run, layout)) === 0) return {}
145
+ await this.publish(run, layout)
146
+ return { branch: layout.branch }
147
+ }
148
+
149
+ /** Best-effort reclamation of a run's remote worktree, branch and base ref. */
150
+ async cleanup(run: SshWorkspaceRun): Promise<void> {
151
+ const layout = this.layoutFor(run)
152
+ const lockKey = `${run.host}:${layout.cacheDir}`
153
+ await withCacheLock(lockKey, async () => {
154
+ try {
155
+ await execRemote(run, removeWorktreeCommand(layout))
156
+ } catch {
157
+ // Best-effort cleanup on card deletion.
158
+ }
159
+ })
160
+ }
161
+
162
+ /**
163
+ * Put the repository in the cache and pin the commit the branch starts from.
164
+ * @param run - the run being prepared.
165
+ * @param layout - the run's paths.
166
+ * @returns the ref or commit `git worktree add` branches from.
167
+ */
168
+ protected abstract seed(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<string>
169
+
170
+ /**
171
+ * Publish the run branch where this source keeps its results.
172
+ * @param run - the settled run.
173
+ * @param layout - the run's paths.
174
+ */
175
+ protected abstract publish(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<void>
176
+
177
+ /**
178
+ * Describe what the source did not send, for the card to explain.
179
+ * @param run - the run being prepared.
180
+ * @returns the note to merge into the preparation; nothing by default.
181
+ */
182
+ protected async sourceNote(_run: SshWorkspaceRun): Promise<{ untrackedFiles?: number }> {
183
+ return {}
184
+ }
185
+
186
+ /**
187
+ * Read how many commits the run branch carries past the commit it started from.
188
+ * @param run - the run being collected.
189
+ * @param layout - the run's paths.
190
+ * @returns the commit count.
191
+ * @throws SshWorkspaceError when the count could not be read as one.
192
+ */
193
+ private async countRunCommits(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<number> {
194
+ const what = `reading the commits of ${layout.branch}`
195
+ const result = await execRemoteChecked(run, countRunCommitsCommand(layout), what)
196
+ const text = result.stdout.trim()
197
+ if (!/^\d+$/.test(text)) {
198
+ throw new SshWorkspaceError(`${what} returned no count: ${boundedLine(result.stdout) ?? 'empty output'}`)
199
+ }
200
+ return Number(text)
201
+ }
202
+ }
203
+
204
+ /** A repository the host clones for itself; the run's branch is pushed back. */
205
+ export class GitUrlWorkspaceStrategy extends GitWorkspaceStrategyBase {
206
+ /** The pinned url source. */
207
+ private readonly source: UrlSource
208
+
209
+ /**
210
+ * @param source - repository URL the host can reach, and its optional base.
211
+ */
212
+ constructor(source: UrlSource) {
213
+ super(`url:${source.url}`)
214
+ this.source = source
215
+ }
216
+
217
+ protected async seed(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<string> {
218
+ const startRef = remoteStartRef(this.source)
219
+ const displayUrl = redactGitUrl(this.source.url)
220
+ await execRemoteChecked(run, fetchUrlCommand(layout, this.source.url), `fetching ${displayUrl}`)
221
+ await execRemoteChecked(run, pinBaseCommand(layout, startRef), `pinning the base of ${layout.branch}`)
222
+ // Branch from the immutable per-run `layout.baseRef` rather than the
223
+ // shared mutable `startRef` so a concurrent fetch can never skew base..branch.
224
+ return layout.baseRef
225
+ }
226
+
227
+ protected async publish(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<void> {
228
+ const displayUrl = redactGitUrl(this.source.url)
229
+ const what = `pushing ${layout.branch} to ${displayUrl}`
230
+ await execRemoteChecked(run, pushBranchCommand(layout, this.source.url), what)
231
+ }
232
+ }
233
+
234
+ /** The local workspace repository, sent as a bundle and fetched back as one. */
235
+ export class GitWorkspaceSourceStrategy extends GitWorkspaceStrategyBase {
236
+ /** The pinned workspace source. */
237
+ private readonly source: WorkspaceSource
238
+
239
+ /**
240
+ * @param source - workspace whose local repository the run starts from.
241
+ */
242
+ constructor(source: WorkspaceSource) {
243
+ super(`workspace:${source.workspaceId}`)
244
+ this.source = source
245
+ }
246
+
247
+ protected async sourceNote(run: SshWorkspaceRun): Promise<{ untrackedFiles: number }> {
248
+ return { untrackedFiles: await countUntrackedFiles(this.requireRepository(run), run.signal) }
249
+ }
250
+
251
+ protected async seed(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<string> {
252
+ const repository = this.requireRepository(run)
253
+ const scratch = await mkdtemp(join(tmpdir(), `${SCRATCH_PREFIX}${layout.runId}-`))
254
+ try {
255
+ const bundlePath = join(scratch, 'workspace.bundle')
256
+ const snapshot = await createWorkspaceBundle({ repository, bundlePath, signal: run.signal })
257
+ const remoteBundle = `${layout.bundlesDir}/${layout.runId}.bundle`
258
+ await execRemoteChecked(run, shellEnsureDir(layout.bundlesDir), 'creating the bundle directory')
259
+ await uploadToHost(run, bundlePath, remoteBundle)
260
+ try {
261
+ await execRemoteChecked(run, fetchBundleCommand(layout, remoteBundle), 'sending the workspace bundle')
262
+ await execRemoteChecked(run, pinBaseCommand(layout, snapshot.base), `pinning the base of ${layout.branch}`)
263
+ } finally {
264
+ await removeRemoteFile(run, remoteBundle)
265
+ }
266
+ return snapshot.base
267
+ } finally {
268
+ await rm(scratch, { recursive: true, force: true })
269
+ }
270
+ }
271
+
272
+ protected async publish(run: SshWorkspaceRun, layout: GitWorkspaceLayout): Promise<void> {
273
+ const repository = this.requireRepository(run)
274
+ const remoteBundle = `${layout.bundlesDir}/${layout.runId}-result.bundle`
275
+ const scratch = await mkdtemp(join(tmpdir(), `${SCRATCH_PREFIX}${layout.runId}-`))
276
+ try {
277
+ const bundlePath = join(scratch, 'result.bundle')
278
+ await execRemoteChecked(run, bundleResultCommand(layout, remoteBundle), `bundling ${layout.branch}`)
279
+ try {
280
+ await downloadFromHost(run, remoteBundle, bundlePath)
281
+ await fetchRunBranch({ repository, bundlePath, branchRef: layout.branchRef, signal: run.signal })
282
+ } finally {
283
+ await removeRemoteFile(run, remoteBundle)
284
+ }
285
+ } finally {
286
+ await rm(scratch, { recursive: true, force: true })
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Read the local repository the run starts from.
292
+ * @param run - the run being served.
293
+ * @returns the absolute local repository root.
294
+ * @throws SshWorkspaceError when the run carries no resolved repository.
295
+ */
296
+ private requireRepository(run: SshWorkspaceRun): string {
297
+ const repository = run.localRepository
298
+ if (repository === undefined || repository === '') {
299
+ throw new SshWorkspaceError(
300
+ `the workspace repository of ${this.source.workspaceId} was not resolved for this run`,
301
+ )
302
+ }
303
+ return repository
304
+ }
305
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Runs in a remote directory the user already has.
3
+ *
4
+ * The pinned directory is the whole strategy: nothing is created, copied or
5
+ * versioned, so the agent's changes land where the user pointed and `collect`
6
+ * has nothing to bring back. An absent directory fails the run instead of being
7
+ * created, because a typo in a path must not turn into a silently new, empty
8
+ * place to work in.
9
+ *
10
+ * @module dsh-task-board-ssh/host/workspace/in-place
11
+ */
12
+ import type { SshWorkspaceCollection, SshWorkspaceRun } from '../../core/workspace.ts'
13
+ import { SshWorkspaceError } from './errors.ts'
14
+ import { directoryProbeCommand } from './remote-git.ts'
15
+ import { probeRemote } from './remote.ts'
16
+ import type { SshWorkspacePreparationNote, SshWorkspaceStrategyWithNote } from './types.ts'
17
+
18
+ /** The pinned remote directory, checked but never created. */
19
+ export class InPlaceWorkspaceStrategy implements SshWorkspaceStrategyWithNote {
20
+ readonly kind = 'in-place' as const
21
+
22
+ /** The directory the card pinned. */
23
+ private readonly path: string
24
+
25
+ /**
26
+ * @param path - absolute remote directory the run works in.
27
+ * @throws SshWorkspaceError when the path is not absolute.
28
+ */
29
+ constructor(path: string) {
30
+ if (!path.startsWith('/')) {
31
+ throw new SshWorkspaceError(`the pinned remote directory must be an absolute path: ${path}`)
32
+ }
33
+ this.path = path
34
+ }
35
+
36
+ /**
37
+ * Check that the pinned directory exists and hand it back.
38
+ * @param run - the run being prepared.
39
+ * @returns the pinned directory as the working directory.
40
+ * @throws SshWorkspaceError when it is missing or the host is unreachable.
41
+ */
42
+ async prepare(run: SshWorkspaceRun): Promise<SshWorkspacePreparationNote> {
43
+ if (!(await probeRemote(run, directoryProbeCommand(this.path)))) {
44
+ throw new SshWorkspaceError(
45
+ `the pinned remote directory does not exist and an in-place workspace never creates it: ${this.path}`,
46
+ )
47
+ }
48
+ return { cwd: this.path }
49
+ }
50
+
51
+ /**
52
+ * Collect nothing: in-place work stays where it was made.
53
+ * @returns an empty collection, because files in place are already the result.
54
+ */
55
+ async collect(): Promise<SshWorkspaceCollection> {
56
+ return {}
57
+ }
58
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The workspace strategies behind one factory.
3
+ *
4
+ * `in-place` and `git` are the two mechanisms the proposal settled; the git
5
+ * mechanism splits by where its repository comes from, because only the
6
+ * workspace source needs a local repository and only it brings a branch back
7
+ * into one. The split happens here and nowhere else, so the run engine holds
8
+ * one strategy per pinned target and never a condition of its own.
9
+ *
10
+ * The source is read from the target, not from the run: a run's `source` field
11
+ * repeats what the card pinned, and one authority for "which repository is this
12
+ * run about" is what keeps `prepare` and `collect` from ever disagreeing.
13
+ *
14
+ * @module dsh-task-board-ssh/host/workspace
15
+ */
16
+ import type { SshWorkspaceTarget } from '../../core/target.ts'
17
+ import { GitUrlWorkspaceStrategy, GitWorkspaceSourceStrategy } from './git.ts'
18
+ import { InPlaceWorkspaceStrategy } from './in-place.ts'
19
+ import type { SshWorkspaceStrategyWithNote } from './types.ts'
20
+
21
+ /**
22
+ * Build the strategy one pinned target names.
23
+ *
24
+ * @param target - filesystem mechanism the card pins, with its source.
25
+ * @returns the strategy for that mechanism; assignable to the frozen
26
+ * `SshWorkspaceStrategy`, and narrowed to a preparation that carries the
27
+ * untracked-file note.
28
+ */
29
+ export function createSshWorkspaceStrategy(target: SshWorkspaceTarget): SshWorkspaceStrategyWithNote {
30
+ if (target.kind === 'in-place') return new InPlaceWorkspaceStrategy(target.path)
31
+ return target.source.kind === 'url'
32
+ ? new GitUrlWorkspaceStrategy(target.source)
33
+ : new GitWorkspaceSourceStrategy(target.source)
34
+ }
35
+
36
+ export type { SshWorkspacePreparationNote, SshWorkspaceStrategyWithNote } from './types.ts'
37
+ export { SshWorkspaceError } from './errors.ts'
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Where one git run lives on the remote host, derived from the run alone.
3
+ *
4
+ * Nothing in here is persisted: every path and ref is recomputed from the run's
5
+ * `stateDir` and `runId`, which is what lets `collect` run in a later process
6
+ * than `prepare` and still find the same worktree, branch and base commit. A
7
+ * bare cache is shared by every run of one source on one host, so a second run
8
+ * of the same repository transfers only the commits it does not already have.
9
+ *
10
+ * @module dsh-task-board-ssh/host/workspace/layout
11
+ */
12
+ import { createHash } from 'node:crypto'
13
+ import { isRunId } from '../../core/launcher.ts'
14
+ import type { SshWorkspaceRun } from '../../core/workspace.ts'
15
+ import { SshWorkspaceError } from './errors.ts'
16
+
17
+ /** Branch prefix every git run commits on: `dsh-task/<runId>`. */
18
+ export const RUN_BRANCH_PREFIX = 'dsh-task/'
19
+
20
+ /** Ref namespace recording the commit a run's branch started from. */
21
+ const BASE_REF_PREFIX = 'refs/dsh-base/'
22
+
23
+ /** Length of a cache directory's digest, in hex characters. */
24
+ const CACHE_KEY_LENGTH = 16
25
+
26
+ /** A run id shape git refuses in a ref, on top of the launcher's grammar. */
27
+ const REF_UNSAFE_RUN_ID = /\.\.|\.lock$|^\.|\.$/
28
+
29
+ /** Paths and refs one git run uses. */
30
+ export interface GitWorkspaceLayout {
31
+ /** Absolute remote state directory the provider owns on the host. */
32
+ stateDir: string
33
+ /** Run identifier every derived name carries. */
34
+ runId: string
35
+ /** Directory holding one bare cache per repository source. */
36
+ reposDir: string
37
+ /** Bare cache of this run's repository. */
38
+ cacheDir: string
39
+ /** Directory holding one worktree per run. */
40
+ workspacesDir: string
41
+ /** Worktree the agent works in. */
42
+ worktreeDir: string
43
+ /** Directory bundles travel through. */
44
+ bundlesDir: string
45
+ /** Branch name the run commits on. */
46
+ branch: string
47
+ /** Full ref of {@link branch}. */
48
+ branchRef: string
49
+ /** Ref pinning the commit the branch started from. */
50
+ baseRef: string
51
+ }
52
+
53
+ /**
54
+ * Short digest of one repository's identity, used as its cache directory name.
55
+ *
56
+ * A digest rather than the URL itself: a clone URL may carry credentials, and
57
+ * a path or a workspace id may carry characters a directory name should not.
58
+ * @param identity - what makes the source unique on this host.
59
+ * @returns sixteen lower-case hex characters.
60
+ */
61
+ export function cacheKey(identity: string): string {
62
+ return createHash('sha256').update(identity).digest('hex').slice(0, CACHE_KEY_LENGTH)
63
+ }
64
+
65
+ /**
66
+ * Refuse a run id that cannot be a git ref component.
67
+ *
68
+ * The launcher's grammar already bounds the characters; git additionally
69
+ * refuses `..`, a leading or trailing dot and a `.lock` suffix, and a run id
70
+ * that reached `git worktree add` with one of those would fail far from here.
71
+ * @param runId - candidate run identifier.
72
+ * @returns the run id, unchanged.
73
+ * @throws SshWorkspaceError when git could not name a branch after it.
74
+ */
75
+ export function assertRefSafeRunId(runId: string): string {
76
+ if (!isRunId(runId)) throw new SshWorkspaceError(`invalid run id: ${runId}`)
77
+ if (REF_UNSAFE_RUN_ID.test(runId)) {
78
+ throw new SshWorkspaceError(`the run id cannot name a git branch: ${runId}`)
79
+ }
80
+ return runId
81
+ }
82
+
83
+ /**
84
+ * Require one absolute remote directory, without its trailing slashes.
85
+ * @param path - candidate directory.
86
+ * @param what - which directory it is, for the diagnostic.
87
+ * @returns the path with trailing slashes removed.
88
+ * @throws SshWorkspaceError when the path is relative or is the filesystem root.
89
+ */
90
+ export function assertRemoteDirectory(path: string, what: string): string {
91
+ if (!path.startsWith('/')) throw new SshWorkspaceError(`${what} must be an absolute remote path: ${path}`)
92
+ const trimmed = path.replace(/\/+$/, '')
93
+ if (trimmed === '') throw new SshWorkspaceError(`${what} cannot be the filesystem root`)
94
+ return trimmed
95
+ }
96
+
97
+ /**
98
+ * Derive every path and ref one git run uses.
99
+ * @param run - the run being prepared or collected.
100
+ * @param sourceIdentity - what makes the repository source unique on this host.
101
+ * @returns the run's layout.
102
+ * @throws SshWorkspaceError when the run carries a path or id git cannot use.
103
+ */
104
+ export function gitWorkspaceLayout(run: SshWorkspaceRun, sourceIdentity: string): GitWorkspaceLayout {
105
+ const stateDir = assertRemoteDirectory(run.stateDir, 'the remote state directory')
106
+ const runId = assertRefSafeRunId(run.runId)
107
+ const branch = `${RUN_BRANCH_PREFIX}${runId}`
108
+ const reposDir = `${stateDir}/repos`
109
+ const workspacesDir = `${stateDir}/workspaces`
110
+ return {
111
+ stateDir,
112
+ runId,
113
+ reposDir,
114
+ cacheDir: `${reposDir}/${cacheKey(sourceIdentity)}`,
115
+ workspacesDir,
116
+ worktreeDir: `${workspacesDir}/${runId}`,
117
+ bundlesDir: `${stateDir}/bundles`,
118
+ branch,
119
+ branchRef: `refs/heads/${branch}`,
120
+ baseRef: `${BASE_REF_PREFIX}${runId}`,
121
+ }
122
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * The local half of the workspace strategies: git on `node:child_process`.
3
+ *
4
+ * Every call is `execFile` with an argument vector, so no path, ref or branch
5
+ * name ever passes through a shell on this side either. Two operations touch
6
+ * the workspace repository, and neither can change what the user is working on:
7
+ * `git stash create` writes objects and returns a commit without touching the
8
+ * working tree, the index, a ref or the stash list, and `git fetch` writes one
9
+ * new ref plus objects, with `--no-write-fetch-head` so not even
10
+ * `.git/FETCH_HEAD` moves. Nothing here checks out, resets or stashes.
11
+ *
12
+ * @module dsh-task-board-ssh/host/workspace/local-git
13
+ */
14
+ import { execFile } from 'node:child_process'
15
+ import { SshWorkspaceError, boundedLine } from './errors.ts'
16
+
17
+ /** Ceiling on one local git command's captured output, in bytes. */
18
+ const MAX_OUTPUT_BYTES = 32 * 1024 * 1024
19
+
20
+ /** Object name shape a bundle's start commit has between here and the host. */
21
+ const COMMIT_RE = /^[0-9a-f]{40,64}$/
22
+
23
+ /** What a working-tree snapshot found, and what it left behind. */
24
+ export interface LocalWorkspaceSnapshot {
25
+ /** Commit `HEAD` points at. */
26
+ head: string
27
+ /** Commit the run branch starts from: the snapshot when dirty, `head` otherwise. */
28
+ base: string
29
+ /** Whether tracked but uncommitted changes were folded in. */
30
+ dirty: boolean
31
+ }
32
+
33
+ /**
34
+ * Read the diagnosis out of a failed git invocation.
35
+ * @param error - what `execFile` reported.
36
+ * @returns one bounded line.
37
+ */
38
+ function describeGitFailure(error: unknown): string {
39
+ const stderr = (error as { stderr?: unknown }).stderr
40
+ if (typeof stderr === 'string') {
41
+ const line = boundedLine(stderr)
42
+ if (line !== undefined) return line
43
+ }
44
+ const message = error instanceof Error ? error.message : String(error)
45
+ return boundedLine(message) ?? 'unknown failure'
46
+ }
47
+
48
+ /**
49
+ * Run one git command against one repository.
50
+ * @param repository - path handed to `git -C`, so no working directory is shared.
51
+ * @param args - git arguments, unquoted and unjoined.
52
+ * @param signal - cancellation of the run this command serves.
53
+ * @returns captured standard output.
54
+ * @throws SshWorkspaceError when git failed, or the abort itself when cancelled.
55
+ */
56
+ export async function runLocalGit(repository: string, args: readonly string[], signal?: AbortSignal): Promise<string> {
57
+ const argv = ['--no-pager', '-C', repository, ...args]
58
+ return await new Promise<string>((resolve, reject) => {
59
+ execFile('git', argv, { encoding: 'utf8', maxBuffer: MAX_OUTPUT_BYTES, signal }, (error, stdout) => {
60
+ if (error === null) {
61
+ resolve(stdout)
62
+ return
63
+ }
64
+ if (error.name === 'AbortError' || (error as { code?: unknown }).code === 'ABORT_ERR') {
65
+ reject(error)
66
+ return
67
+ }
68
+ reject(new SshWorkspaceError(`git ${args.join(' ')} failed: ${describeGitFailure(error)}`, { cause: error }))
69
+ })
70
+ })
71
+ }
72
+
73
+ /**
74
+ * Require one path to be the root of a working tree.
75
+ * @param repository - candidate repository path.
76
+ * @param signal - cancellation of the run this command serves.
77
+ * @throws SshWorkspaceError when the path is not a work tree of any repository.
78
+ */
79
+ export async function assertLocalWorkTree(repository: string, signal?: AbortSignal): Promise<void> {
80
+ const inside = (await runLocalGit(repository, ['rev-parse', '--is-inside-work-tree'], signal)).trim()
81
+ if (inside !== 'true') throw new SshWorkspaceError(`the local workspace is not a git work tree: ${repository}`)
82
+ }
83
+
84
+ /**
85
+ * Count the untracked files a bundle does not carry.
86
+ *
87
+ * Ignored files stay out: a `node_modules` is not something the card has to
88
+ * warn about, and counting it would make the number meaningless.
89
+ * @param repository - local workspace repository.
90
+ * @param signal - cancellation of the run this command serves.
91
+ * @returns how many untracked, non-ignored files the working tree holds.
92
+ */
93
+ export async function countUntrackedFiles(repository: string, signal?: AbortSignal): Promise<number> {
94
+ const listing = await runLocalGit(repository, ['ls-files', '--others', '--exclude-standard', '-z'], signal)
95
+ return listing.split('\u0000').filter(entry => entry !== '').length
96
+ }
97
+
98
+ /**
99
+ * Refuse an object name that is not one.
100
+ * @param commit - candidate commit read from git.
101
+ * @returns the commit, unchanged.
102
+ * @throws SshWorkspaceError when it has the wrong shape, so it never reaches a host.
103
+ */
104
+ function assertCommit(commit: string): string {
105
+ if (!COMMIT_RE.test(commit)) {
106
+ throw new SshWorkspaceError(`git reported an object name that is not a commit: ${commit}`)
107
+ }
108
+ return commit
109
+ }
110
+
111
+ /**
112
+ * Bundle the state a remote run starts from.
113
+ *
114
+ * `HEAD` is the history the bundle carries. When the working tree holds tracked
115
+ * uncommitted changes, their snapshot commit travels with it, so the run starts
116
+ * from what the user has on disk rather than from what they last committed.
117
+ * @param input - repository, destination and cancellation.
118
+ * @returns the commit the run branch starts from, and whether it was a snapshot.
119
+ * @throws SshWorkspaceError when the repository has no commit or git refused.
120
+ */
121
+ export async function createWorkspaceBundle(input: {
122
+ /** Local workspace repository. */
123
+ repository: string
124
+ /** Local path the bundle is written to. */
125
+ bundlePath: string
126
+ /** Cancellation of the run this bundle serves. */
127
+ signal?: AbortSignal
128
+ }): Promise<LocalWorkspaceSnapshot> {
129
+ const { repository, bundlePath, signal } = input
130
+ await assertLocalWorkTree(repository, signal)
131
+ const head = assertCommit((await runLocalGit(repository, ['rev-parse', '--verify', 'HEAD'], signal)).trim())
132
+ const snapshot = (await runLocalGit(repository, ['stash', 'create'], signal)).trim()
133
+ const dirty = snapshot !== ''
134
+ const base = dirty ? assertCommit(snapshot) : head
135
+ const revisions = dirty ? [base, 'HEAD'] : ['HEAD']
136
+ await runLocalGit(repository, ['bundle', 'create', '--quiet', bundlePath, ...revisions], signal)
137
+ return { head, base, dirty }
138
+ }
139
+
140
+ /**
141
+ * Fetch the branch a host bundled back into the local repository.
142
+ *
143
+ * The working tree, the index, `HEAD` and the stash list are untouched: a fetch
144
+ * writes the branch ref and objects only, and the run's result stays a branch
145
+ * the user can inspect before doing anything with it.
146
+ * @param input - repository, bundle and destination branch.
147
+ * @throws SshWorkspaceError when the bundle does not apply or git refused.
148
+ */
149
+ export async function fetchRunBranch(input: {
150
+ /** Local workspace repository. */
151
+ repository: string
152
+ /** Local path of the downloaded bundle. */
153
+ bundlePath: string
154
+ /** Branch ref the bundle's branch is written to. */
155
+ branchRef: string
156
+ /** Cancellation of the run this fetch serves. */
157
+ signal?: AbortSignal
158
+ }): Promise<void> {
159
+ await runLocalGit(
160
+ input.repository,
161
+ ['fetch', '--no-write-fetch-head', '--no-tags', input.bundlePath, `+${input.branchRef}:${input.branchRef}`],
162
+ input.signal,
163
+ )
164
+ }