@alpacachen/dsh-kanban 1.11.3 → 1.12.0

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.
@@ -0,0 +1,133 @@
1
+ import { constants } from 'node:fs'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, unlink } from 'node:fs/promises'
4
+ import { join, relative, resolve, sep } from 'node:path'
5
+
6
+ const fail = () => { throw Object.assign(new Error('任务产物目录或文件不可用,请检查目录后重试。'), { code: 'WF_TASK_FILES_UNAVAILABLE' }) }
7
+ const fileVersion = stat => `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`
8
+ const safeId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,200}$/.test(value)
9
+
10
+ /** Only clean directories after the durable deletion receipt has stopped and hidden the Task. */
11
+ export async function deleteTaskDirectory(task) {
12
+ if (!safeId(task.id)) fail()
13
+ try {
14
+ if (await realpath(task.rootPath) !== task.rootPath) fail()
15
+ let directory = task.rootPath
16
+ for (const name of ['.dsh', 'workflow-artifacts', task.id]) {
17
+ directory = join(directory, name)
18
+ let stat
19
+ try { stat = await lstat(directory) } catch (error) { if (error.code === 'ENOENT') return; throw error }
20
+ if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(directory) !== directory) fail()
21
+ }
22
+ await rm(directory, { recursive: true, force: true })
23
+ } catch { fail() }
24
+ }
25
+
26
+ /** Task identities come from the store, never from a caller-supplied filesystem root. */
27
+ export async function ensureTaskDirectory(task) {
28
+ if (!safeId(task.id)) fail()
29
+ try {
30
+ const root = await realpath(task.rootPath)
31
+ if (root !== task.rootPath) fail()
32
+ let current = root
33
+ for (const name of ['.dsh', 'workflow-artifacts', task.id]) {
34
+ current = join(current, name)
35
+ try { await mkdir(current) } catch (error) { if (error.code !== 'EEXIST') throw error }
36
+ const stat = await lstat(current)
37
+ if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(current) !== current) fail()
38
+ }
39
+ return current
40
+ } catch { fail() }
41
+ }
42
+
43
+ /** Do not follow directory links into another Task or out of the project. */
44
+ export async function taskFilePath(task, filePath) {
45
+ const directory = await ensureTaskDirectory(task)
46
+ if (typeof filePath !== 'string' || !filePath || filePath.includes('\\') || filePath.includes('\0')) fail()
47
+ const path = resolve(directory, filePath), local = relative(directory, path)
48
+ if (!local || local.startsWith(`..${sep}`) || local === '..' || local !== filePath.split('/').join(sep)) fail()
49
+ try {
50
+ let current = directory
51
+ for (const name of local.split(sep)) {
52
+ current = join(current, name)
53
+ if ((await lstat(current)).isSymbolicLink()) fail()
54
+ }
55
+ if (!(await lstat(path)).isFile() || await realpath(path) !== path) fail()
56
+ return { directory, path }
57
+ } catch { fail() }
58
+ }
59
+
60
+ export async function listTaskFiles(task, { includeStageResults = false } = {}) {
61
+ const directory = await ensureTaskDirectory(task), files = []
62
+ async function walk(path) {
63
+ for (const entry of await readdir(path, { withFileTypes: true })) {
64
+ const child = join(path, entry.name)
65
+ if (!includeStageResults && path === directory && entry.name === '.workflow-results') continue
66
+ if (entry.isSymbolicLink()) continue
67
+ if (entry.isDirectory()) {
68
+ if ((await lstat(child)).isSymbolicLink() || await realpath(child) !== child) continue
69
+ await walk(child)
70
+ } else if (entry.isFile()) {
71
+ try {
72
+ const stat = await lstat(child)
73
+ if (!stat.isFile() || stat.isSymbolicLink()) continue
74
+ const name = relative(directory, child).split(sep).join('/')
75
+ const stageResult = name.startsWith('.workflow-results/')
76
+ const attempt = stageResult && task.attempts?.find(attempt => `${attempt.id}.md` === entry.name)
77
+ const visit = attempt && task.visits?.find(visit => visit.id === attempt.visitId)
78
+ const stage = visit && task.definition?.stages.find(stage => stage.id === visit.stageId)
79
+ files.push({ path: name, name: entry.name, version: fileVersion(stat), byteLength: stat.size, updatedAt: stat.mtimeMs, kind: stageResult ? 'stage-result' : 'file', ...(stage ? { stageTitle: stage.title, effective: task.effectiveArtifacts?.some(artifact => artifact.attemptId === attempt.id) ?? false } : {}) })
80
+ } catch (error) { if (error.code !== 'ENOENT') throw error }
81
+ }
82
+ }
83
+ }
84
+ try { await walk(directory) } catch { fail() }
85
+ return { directory, files: files.sort((a, b) => a.path.localeCompare(b.path)) }
86
+ }
87
+
88
+ /** The attachment is immutable; this reserved copy can be repaired from verified bytes. */
89
+ export async function saveStageResult(task, attemptId, text) {
90
+ if (!safeId(attemptId)) fail()
91
+ const directory = await ensureTaskDirectory(task), results = join(directory, '.workflow-results')
92
+ try {
93
+ try { await mkdir(results) } catch (error) { if (error.code !== 'EEXIST') throw error }
94
+ if ((await lstat(results)).isSymbolicLink() || await realpath(results) !== results) fail()
95
+ const relativePath = `.workflow-results/${attemptId}.md`
96
+ let file
97
+ try { file = await open(join(results, `${attemptId}.md`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600) }
98
+ catch (error) {
99
+ if (error.code !== 'EEXIST') throw error
100
+ const { path } = await taskFilePath(task, relativePath)
101
+ const existing = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
102
+ let matches
103
+ try { matches = await existing.readFile('utf8') === text } finally { await existing.close() }
104
+ if (matches) return relativePath
105
+ const temporary = join(results, `.${attemptId}-${randomUUID()}.tmp`)
106
+ try {
107
+ const replacement = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
108
+ try { await replacement.writeFile(text, 'utf8'); await replacement.sync() } finally { await replacement.close() }
109
+ await rename(temporary, path)
110
+ } finally { await rm(temporary, { force: true }) }
111
+ return relativePath
112
+ }
113
+ try { await file.writeFile(text, 'utf8'); await file.sync() } finally { await file.close() }
114
+ return relativePath
115
+ } catch { fail() }
116
+ }
117
+
118
+
119
+ /** Conditional deletion of a single regular file; canonical history attachments stay intact. */
120
+ export async function deleteTaskFile(task, filePath, expectedVersion) {
121
+ if (typeof filePath === 'string' && filePath.split('/')[0] === '.workflow-results') {
122
+ throw Object.assign(new Error('阶段执行报告是只读历史,请在阶段详情中查看。'), { code: 'WF_FILE_READ_ONLY' })
123
+ }
124
+ const { path } = await taskFilePath(task, filePath)
125
+ if (typeof expectedVersion !== 'string' || !expectedVersion) fail()
126
+ try {
127
+ const stat = await lstat(path)
128
+ if (!stat.isFile() || stat.isSymbolicLink()) fail()
129
+ if (fileVersion(stat) !== expectedVersion) throw Object.assign(new Error('文件已更新,请刷新产物列表后重新确认删除。'), { code: 'WF_FILE_CHANGED' })
130
+ await unlink(path)
131
+ } catch (error) { if (error.code === 'WF_FILE_CHANGED') throw error; fail() }
132
+ return { path: filePath, deleted: true }
133
+ }
Binary file
Binary file
Binary file
Binary file