@isdou/dsh-journal 0.0.0-stage → 0.1.4

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,226 @@
1
+ /** Read the Host's live-preferred logical corpus without opening or mutating Sessions. */
2
+ import { resolve as resolvePath } from 'node:path';
3
+
4
+ const COVERAGE = '改动统计仅包含会话中能确认已执行的文件工具结果;终端命令、外部修改及未持久化的工作区快照可能不完整,不代表全部 Git 改动或净增删行数。';
5
+
6
+ function textOf(message) {
7
+ return (Array.isArray(message?.content) ? message.content : [])
8
+ .filter(block => block?.type === 'text' && typeof block.text === 'string')
9
+ .map(block => block.text).join('\n');
10
+ }
11
+
12
+ function jsonArguments(value) {
13
+ if (typeof value !== 'string') return {};
14
+ try { const parsed = JSON.parse(value); return parsed && typeof parsed === 'object' ? parsed : {}; }
15
+ catch { return {}; }
16
+ }
17
+
18
+ function record(value) { return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
19
+ function inRange(time, range) { return Number.isFinite(time) && time >= range.startMs && time < range.endMs; }
20
+ function abort(signal) { signal?.throwIfAborted(); }
21
+ function sameFilePath(left, right, cwd) { return left === right || (cwd && resolvePath(cwd, left) === resolvePath(cwd, right)); }
22
+ function recordedArguments(call) {
23
+ return typeof call?.data?.arguments === 'string' && call.data.arguments.length
24
+ ? `\n调用参数(原始记录,仅供引用):\n${call.data.arguments}` : '';
25
+ }
26
+
27
+ /** Provider call ids can repeat in later requests; never let a future call replace a historical one. */
28
+ function pairToolEvents(events) {
29
+ const pending = new Map(), callsByResult = new Map(), resultsByCall = new Map();
30
+ const coordinate = event => Number.isInteger(event.data?.turn) && Number.isInteger(event.data?.step)
31
+ ? `${event.data.turn}:${event.data.step}` : undefined;
32
+ for (const event of events) {
33
+ if (event.type === 'tool/call' && typeof event.data?.callId === 'string') {
34
+ const list = pending.get(event.data.callId) ?? [];
35
+ list.push(event); pending.set(event.data.callId, list);
36
+ } else if (event.type === 'tool/result') {
37
+ const message = event.data?.message;
38
+ const callId = message?.toolCallId ?? message?.source?.callId;
39
+ const list = pending.get(callId);
40
+ if (!list?.length) continue;
41
+ const position = coordinate(event);
42
+ let index = position === undefined ? list.length - 1 : list.findIndex(call => coordinate(call) === position);
43
+ if (index < 0) index = list.findLastIndex(call => coordinate(call) === undefined);
44
+ if (index < 0) continue;
45
+ const [call] = list.splice(index, 1);
46
+ callsByResult.set(event, call); resultsByCall.set(call, event);
47
+ }
48
+ }
49
+ return { callsByResult, resultsByCall };
50
+ }
51
+
52
+ /** A conservative section locator, used only after a result confirms the corresponding path. */
53
+ function patchSections(input, cwd) {
54
+ const sections = new Map();
55
+ const remember = (filePath, section) => {
56
+ sections.set(filePath, section);
57
+ if (cwd) sections.set(resolvePath(cwd, filePath), section);
58
+ };
59
+ let current;
60
+ for (const line of (typeof input === 'string' ? input : '').split('\n')) {
61
+ const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line);
62
+ if (header) {
63
+ current = { path: header[2], operation: { Add: 'create', Update: 'update', Delete: 'delete' }[header[1]], lines: [] };
64
+ remember(current.path, current);
65
+ } else if (current && line.startsWith('*** Move to: ')) {
66
+ current.operation = 'move'; current.destination = line.slice(13); remember(current.destination, current);
67
+ } else if (current && !line.startsWith('*** End Patch')) current.lines.push(line);
68
+ }
69
+ return sections;
70
+ }
71
+
72
+ function appliedDiffs(meta) {
73
+ return (Array.isArray(meta.diffs) ? meta.diffs : []).filter(diff =>
74
+ diff && typeof diff.path === 'string' && (diff.oldText === null || typeof diff.oldText === 'string')
75
+ && typeof diff.newText === 'string');
76
+ }
77
+
78
+ function changeText(operation, path, diffs, fallback) {
79
+ const label = { create: '创建', update: '修改', delete: '删除', move: '移动', write: '已执行写入', edit: '已执行编辑' }[operation] ?? '修改';
80
+ const body = diffs.length
81
+ ? diffs.map(diff => `改动前(已记录片段):\n${diff.oldText ?? ''}\n改动后(已记录片段):\n${diff.newText}`).join('\n\n')
82
+ : fallback;
83
+ return `${label}文件 ${path}${body ? `\n${body}` : '\n(该记录未包含文件内容差异)'}`;
84
+ }
85
+
86
+ /** Paths requested by a call are never sufficient proof that an apply_patch operation completed. */
87
+ function confirmedChanges(call, result, resultText, warn, cwd) {
88
+ const meta = record(result.data?.meta);
89
+ const args = jsonArguments(call?.data?.arguments);
90
+ const name = call?.data?.name;
91
+ const diffs = appliedDiffs(meta);
92
+ const paths = new Map();
93
+ if (name === 'apply_patch') {
94
+ const sections = patchSections(args.input, cwd);
95
+ let completedBlock = /^Success\. Updated the following files:/m.test(resultText);
96
+ for (const line of resultText.split('\n')) {
97
+ if (line === 'Completed:') { completedBlock = true; continue; }
98
+ if (/^(Failed:|Outcome unknown:|Not executed:)$/.test(line)) { completedBlock = false; continue; }
99
+ const match = completedBlock && /^([AMD]) (.+)$/.exec(line);
100
+ if (match) paths.set(match[2], { operation: { A: 'create', M: 'update', D: 'delete' }[match[1]], status: 'success' });
101
+ }
102
+ // Persisted diffs may also prove a partial move's destination was changed.
103
+ for (const diff of diffs) if (![...paths.keys()].some(filePath => sameFilePath(filePath, diff.path, cwd))) {
104
+ paths.set(diff.path, { operation: 'update', status: meta.stopped ? 'partial' : 'success' });
105
+ }
106
+ if (!paths.size && !/Success\. No operations in patch\./.test(resultText)) warn('补丁工具结果缺少可确认的已完成文件,未将请求中的路径计为成功改动。');
107
+ return [...paths].map(([path, details]) => {
108
+ const section = sections.get(path) ?? (cwd ? sections.get(resolvePath(cwd, path)) : undefined);
109
+ return { path, ...details, text: changeText(section?.operation ?? details.operation, path,
110
+ diffs.filter(diff => sameFilePath(diff.path, path, cwd)), section?.lines.join('\n')) };
111
+ });
112
+ }
113
+ if (name !== 'write' && name !== 'edit') return [];
114
+ const path = typeof meta.path === 'string' ? meta.path
115
+ : diffs[0]?.path ?? (typeof args.file_path === 'string' ? args.file_path : /<path>([^<]+)<\/path>/.exec(resultText)?.[1]);
116
+ if (!path) { warn('文件工具成功结果缺少文件路径,未计为可确认的文件改动。'); return []; }
117
+ const operation = meta.operation === 'create' || /\bCreated file\b/.test(resultText) ? 'create' : 'update';
118
+ const missingComparison = diffs.length === 0 && operation !== 'create';
119
+ if (missingComparison) warn('文件工具已成功执行,但未记录前后差异;已计为文件操作,无法据此判断文件内容是否发生变化。');
120
+ const fallback = name === 'write' && typeof args.content === 'string'
121
+ ? `执行时写入内容:\n${args.content}`
122
+ : name === 'edit' && typeof args.old_string === 'string' && typeof args.new_string === 'string'
123
+ ? `执行时替换片段:\n${args.old_string}\n替换为:\n${args.new_string}` : '';
124
+ return [{ path, status: 'success', text: changeText(missingComparison ? name : operation, path, diffs,
125
+ `${missingComparison ? '前后差异不可用,不能确认内容是否发生变化。\n' : ''}${fallback}`) }];
126
+ }
127
+
128
+ /**
129
+ * Collect all sessions active in the half-open interval [startMs, endMs).
130
+ * Message and result timestamps determine membership, never Session creation time.
131
+ */
132
+ export async function collectActivity(ctx, range, { signal } = {}) {
133
+ if (!Number.isFinite(range?.startMs) || !Number.isFinite(range?.endMs) || range.endMs <= range.startMs) {
134
+ throw new Error('报告时间范围无效。');
135
+ }
136
+ const query = ctx.sessionQuery;
137
+ if (!query?.listSessions || !query?.readSession) throw new Error('宿主未提供 sessionQuery,会话读取服务不可用。');
138
+ abort(signal);
139
+ const records = await query.listSessions(signal);
140
+ if (!Array.isArray(records)) throw new Error('宿主会话列表格式无效。');
141
+ const warnings = new Set([COVERAGE]);
142
+ const sessions = [], evidence = [];
143
+ const stats = { sessionCount: 0, messageCount: 0, toolCount: 0, changeCount: 0, failedToolCount: 0 };
144
+ const seen = new Set();
145
+ for (const entry of records) {
146
+ abort(signal);
147
+ const id = entry?.header?.id;
148
+ if (typeof id !== 'string' || !id) { warnings.add('宿主返回了缺少标识的会话,无法读取该条记录。'); continue; }
149
+ if (seen.has(id)) continue;
150
+ seen.add(id);
151
+ let snapshot;
152
+ try { snapshot = await query.readSession(id); }
153
+ catch (error) {
154
+ abort(signal);
155
+ // Never expose arbitrary Host errors: they may include message bodies or credentials.
156
+ warnings.add(`会话 ${id} 读取失败,报告覆盖不完整。`);
157
+ continue;
158
+ }
159
+ abort(signal);
160
+ if (!Array.isArray(snapshot?.events)) { warnings.add(`会话 ${id} 的事件格式无效,报告覆盖不完整。`); continue; }
161
+ const events = snapshot.events;
162
+ const inherited = Number.isSafeInteger(snapshot.inheritedEventCount) ? snapshot.inheritedEventCount : 0;
163
+ const ownEvents = events.filter(event => !(Number.isFinite(event.seq) && event.seq < inherited));
164
+ const active = ownEvents.filter(event => inRange(event.time, range));
165
+ if (!active.length) continue;
166
+ const titleEvent = events.findLast(event => event.type === 'session/title' && typeof event.data?.title === 'string');
167
+ const title = titleEvent?.data.title ?? entry.title ?? id;
168
+ const cwd = snapshot.session?.cwd ?? entry.header.cwd ?? '';
169
+ const base = { sessionId: id, sessionTitle: title, cwd };
170
+ const sessionEvidence = [];
171
+ const { callsByResult, resultsByCall } = pairToolEvents(events);
172
+ for (const event of active) {
173
+ if (event.type === 'user/message' || event.type === 'assistant/message') {
174
+ const message = event.type === 'user/message' ? event.data : event.data?.message;
175
+ // Host-injected user-role context is not a human instruction.
176
+ if (event.type === 'user/message' && message?.source?.kind && message.source.kind !== 'user') continue;
177
+ const type = event.type === 'user/message' ? 'user' : 'assistant';
178
+ const text = textOf(message);
179
+ sessionEvidence.push({ ...base, time: event.time, type, text: text || '(非文本消息,未读取附件内容)', seq: event.seq });
180
+ stats.messageCount++;
181
+ }
182
+ if (event.type !== 'tool/result') continue;
183
+ const message = event.data?.message;
184
+ const call = callsByResult.get(event);
185
+ const name = call?.data?.name ?? '未识别工具';
186
+ const resultText = textOf(message);
187
+ const meta = record(event.data?.meta);
188
+ const failed = message?.isError === true || event.data?.error !== undefined;
189
+ const partial = !failed && (meta.stopped === true || /^Patch stopped after /m.test(resultText));
190
+ const status = failed ? 'failed' : partial ? 'partial' : message ? 'success' : 'unknown';
191
+ stats.toolCount++;
192
+ if (failed || partial) stats.failedToolCount++;
193
+ sessionEvidence.push({ ...base, time: event.time, type: 'tool', status, toolName: name,
194
+ text: `${name}(${{ failed: '失败', partial: '部分执行后停止', success: '工具返回成功', unknown: '结果未知' }[status]})${recordedArguments(call)}${resultText ? `\n执行结果:\n${resultText}` : ''}`, seq: event.seq });
195
+ if (status === 'unknown') warnings.add(`会话 ${id} 存在缺少有效结果的工具记录,未将其视为已完成改动。`);
196
+ if (failed || status === 'unknown') continue;
197
+ for (const change of confirmedChanges(call, event, resultText, warning => warnings.add(`会话 ${id}:${warning}`), cwd)) {
198
+ sessionEvidence.push({ ...base, time: event.time, type: 'change', ...change, seq: event.seq, toolName: name });
199
+ stats.changeCount++;
200
+ }
201
+ }
202
+ for (const event of active) {
203
+ if (event.type !== 'tool/call') continue;
204
+ const result = resultsByCall.get(event);
205
+ if (result && inRange(result.time, range)) continue;
206
+ // A result after endMs must not retroactively make an in-range call successful.
207
+ if (result && result.time < range.startMs) continue;
208
+ stats.toolCount++;
209
+ const name = event.data?.name ?? '未识别工具';
210
+ sessionEvidence.push({ ...base, time: event.time, type: 'tool', status: 'unknown', toolName: name,
211
+ text: `${name}(所选时间范围内没有完成结果,执行状态未知)${recordedArguments(event)}`, seq: event.seq });
212
+ warnings.add(`会话 ${id} 存在所选范围内未得到完成结果的工具调用,未计为已完成改动。`);
213
+ }
214
+ if (!sessionEvidence.length) continue;
215
+ sessionEvidence.sort((a, b) => a.time - b.time || (a.seq ?? 0) - (b.seq ?? 0));
216
+ sessions.push({ id, title, cwd, messageCount: sessionEvidence.filter(item => item.type === 'user' || item.type === 'assistant').length,
217
+ changeCount: sessionEvidence.filter(item => item.type === 'change').length,
218
+ startTime: sessionEvidence[0].time, endTime: sessionEvidence.at(-1).time });
219
+ evidence.push(...sessionEvidence);
220
+ }
221
+ abort(signal);
222
+ stats.sessionCount = sessions.length;
223
+ evidence.sort((a, b) => a.time - b.time || a.sessionId.localeCompare(b.sessionId) || (a.seq ?? 0) - (b.seq ?? 0));
224
+ sessions.sort((a, b) => b.endTime - a.endTime || a.id.localeCompare(b.id));
225
+ return { range, stats, sessions, evidence, warnings: [...warnings] };
226
+ }
@@ -0,0 +1,26 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ function invalid() {
5
+ return Object.assign(new Error('简报模型偏好无效,请检查 preferences.json 中的 provider 和 model。'), {
6
+ status: 400, code: 'INVALID_PREFERENCES',
7
+ });
8
+ }
9
+
10
+ /** This file stores model identifiers only; credentials remain owned by DSH. */
11
+ export async function loadReportModel(reportRoot) {
12
+ let text;
13
+ try { text = await readFile(join(reportRoot, 'preferences.json'), 'utf8'); }
14
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
15
+ let preferences;
16
+ try { preferences = JSON.parse(text); }
17
+ catch { throw invalid(); }
18
+ if (!preferences || typeof preferences !== 'object' || Array.isArray(preferences)) throw invalid();
19
+ const model = preferences.reportModel;
20
+ if (model === undefined || model === null) return undefined;
21
+ if (typeof model !== 'object' || Array.isArray(model)
22
+ || Object.keys(model).some(key => key !== 'provider' && key !== 'model')
23
+ || typeof model.provider !== 'string' || !model.provider.trim()
24
+ || typeof model.model !== 'string' || !model.model.trim()) throw invalid();
25
+ return Object.freeze({ provider: model.provider.trim(), model: model.model.trim() });
26
+ }
package/lib/range.js ADDED
@@ -0,0 +1,86 @@
1
+ const DAY_MS = 86_400_000;
2
+ const PRESETS = { day: '日报', week: '周报', month: '月报', custom: '工作报告' };
3
+
4
+ function invalid(message) {
5
+ return Object.assign(new Error(message), { status: 400, code: 'INVALID_RANGE' });
6
+ }
7
+
8
+ function calendarDate(value) {
9
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
10
+ throw invalid('日期格式须为 YYYY-MM-DD。');
11
+ }
12
+ const [year, month, day] = value.split('-').map(Number);
13
+ const date = new Date(0);
14
+ date.setUTCFullYear(year, month - 1, day);
15
+ date.setUTCHours(0, 0, 0, 0);
16
+ if (year < 1 || date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
17
+ throw invalid('请选择真实有效的日期。');
18
+ }
19
+ return { value, date, key: year * 10000 + month * 100 + day };
20
+ }
21
+
22
+ function nextCalendarDate(value) {
23
+ const date = new Date(value.date);
24
+ date.setUTCDate(date.getUTCDate() + 1);
25
+ return {
26
+ date,
27
+ key: date.getUTCFullYear() * 10000 + (date.getUTCMonth() + 1) * 100 + date.getUTCDate(),
28
+ };
29
+ }
30
+
31
+ function localDateKey(formatter, milliseconds) {
32
+ const parts = Object.fromEntries(formatter.formatToParts(milliseconds).map(part => [part.type, part.value]));
33
+ const year = parts.era === 'BC' ? 1 - Number(parts.year) : Number(parts.year);
34
+ return year * 10000 + Number(parts.month) * 100 + Number(parts.day);
35
+ }
36
+
37
+ // Find the first instant of a calendar date. Midnight is not always an existing
38
+ // local time (some zones advance their clocks at 00:00), so do not add 24 hours
39
+ // or rely on the host machine's timezone to construct day boundaries.
40
+ function dateBoundary(value, formatter) {
41
+ const nominal = value.date.getTime();
42
+ let low = nominal - 2 * DAY_MS;
43
+ let high = nominal + 2 * DAY_MS;
44
+ while (low < high) {
45
+ const middle = low + Math.floor((high - low) / 2);
46
+ if (localDateKey(formatter, middle) < value.key) low = middle + 1;
47
+ else high = middle;
48
+ }
49
+ return low;
50
+ }
51
+
52
+ export function normalizeRange(input = {}) {
53
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw invalid('请选择报告时间范围。');
54
+ const start = calendarDate(input.start);
55
+ const end = calendarDate(input.end);
56
+ if (start.key > end.key) throw invalid('开始日期不能晚于结束日期。');
57
+
58
+ const preset = input.preset ?? 'custom';
59
+ if (!Object.hasOwn(PRESETS, preset)) throw invalid('不支持的报告类型。');
60
+ const timeZone = input.timeZone ?? 'Asia/Shanghai';
61
+ if (typeof timeZone !== 'string' || !timeZone) throw invalid('请选择有效时区。');
62
+ let formatter;
63
+ try {
64
+ formatter = new Intl.DateTimeFormat('en-US-u-ca-gregory-nu-latn', {
65
+ timeZone, year: 'numeric', month: '2-digit', day: '2-digit', era: 'short',
66
+ });
67
+ } catch {
68
+ throw invalid('请选择有效的 IANA 时区。');
69
+ }
70
+
71
+ const startMs = dateBoundary(start, formatter);
72
+ const endDayStartMs = dateBoundary(end, formatter);
73
+ if (localDateKey(formatter, startMs) !== start.key || localDateKey(formatter, endDayStartMs) !== end.key) {
74
+ throw invalid('该日期在所选时区不存在,请调整时间范围。');
75
+ }
76
+ const endMs = dateBoundary(nextCalendarDate(end), formatter);
77
+ return {
78
+ start: start.value,
79
+ end: end.value,
80
+ timeZone,
81
+ preset,
82
+ startMs,
83
+ endMs,
84
+ label: `${PRESETS[preset]} · ${start.value}${start.value === end.value ? '' : ` — ${end.value}`}`,
85
+ };
86
+ }
@@ -0,0 +1,103 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+
5
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
+
7
+ function problem(status, code, message) {
8
+ return Object.assign(new Error(message), { status, code });
9
+ }
10
+
11
+ function checkedId(id) {
12
+ if (typeof id !== 'string' || !UUID.test(id)) throw problem(400, 'INVALID_REPORT_ID', '报告编号无效。');
13
+ return id.toLowerCase();
14
+ }
15
+
16
+ function metadata(report) {
17
+ const result = {};
18
+ for (const key of ['id', 'title', 'createdAt', 'updatedAt', 'range', 'stats', 'mode', 'modelId']) {
19
+ if (report[key] !== undefined) result[key] = report[key];
20
+ }
21
+ return result;
22
+ }
23
+
24
+ function validMarkdown(report) {
25
+ if (!report || typeof report !== 'object' || Array.isArray(report) || typeof report.markdown !== 'string') {
26
+ throw problem(400, 'INVALID_REPORT', '报告正文须为 Markdown 文本。');
27
+ }
28
+ }
29
+
30
+ export class ReportStore {
31
+ constructor(root) {
32
+ if (typeof root !== 'string' || !root) throw new TypeError('ReportStore requires its own data directory.');
33
+ this.root = resolve(root);
34
+ }
35
+
36
+ async list() {
37
+ let entries;
38
+ try {
39
+ entries = await readdir(this.root, { withFileTypes: true });
40
+ } catch (error) {
41
+ if (error.code === 'ENOENT') return [];
42
+ throw error;
43
+ }
44
+ const reports = [];
45
+ for (const entry of entries) {
46
+ if (!entry.isFile() || !entry.name.endsWith('.json') || !UUID.test(entry.name.slice(0, -5))) continue;
47
+ reports.push(metadata(await this.get(entry.name.slice(0, -5))));
48
+ }
49
+ return reports.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id));
50
+ }
51
+
52
+ async get(id) {
53
+ id = checkedId(id);
54
+ let text;
55
+ try {
56
+ text = await readFile(join(this.root, `${id}.json`), 'utf8');
57
+ } catch (error) {
58
+ if (error.code === 'ENOENT') throw problem(404, 'REPORT_NOT_FOUND', '找不到这份报告。');
59
+ throw error;
60
+ }
61
+ try {
62
+ const report = JSON.parse(text);
63
+ if (!report || report.id !== id || typeof report.markdown !== 'string' || typeof report.createdAt !== 'string') throw new Error();
64
+ return report;
65
+ } catch {
66
+ throw problem(500, 'CORRUPT_REPORT', `本地报告 ${id} 无法读取,请保留文件并检查数据备份。`);
67
+ }
68
+ }
69
+
70
+ async save(report) {
71
+ validMarkdown(report);
72
+ const now = new Date().toISOString();
73
+ const saved = { ...report, id: randomUUID(), createdAt: now, updatedAt: now };
74
+ await this.#write(saved);
75
+ return saved;
76
+ }
77
+
78
+ async update(id, changes) {
79
+ validMarkdown(changes);
80
+ const report = await this.get(id);
81
+ const saved = { ...report, markdown: changes.markdown, updatedAt: new Date().toISOString() };
82
+ await this.#write(saved);
83
+ return saved;
84
+ }
85
+
86
+ async #write(report) {
87
+ let json;
88
+ try {
89
+ json = JSON.stringify(report, null, 2);
90
+ } catch {
91
+ throw problem(400, 'INVALID_REPORT', '报告包含无法保存的数据。');
92
+ }
93
+ await mkdir(this.root, { recursive: true, mode: 0o700 });
94
+ const path = join(this.root, `${report.id}.json`);
95
+ const temporary = join(this.root, `.${report.id}.${randomUUID()}.tmp`);
96
+ try {
97
+ await writeFile(temporary, `${json}\n`, { flag: 'wx', mode: 0o600 });
98
+ await rename(temporary, path);
99
+ } finally {
100
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
101
+ }
102
+ }
103
+ }