Repository navigation
Expand file tree
/
Copy pathartifact-store.js
More file actions
249 lines (224 loc) · 7.14 KB
/
Copy pathartifact-store.js
File metadata and controls
249 lines (224 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
'use strict';
const fs = require('fs/promises');
const path = require('path');
function slug(value) {
return String(value || '')
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'agent';
}
function safeInside(root, target) {
const r = path.resolve(root);
const t = path.resolve(target);
return t === r || t.startsWith(r + path.sep);
}
async function safeInsideReal(root, target) {
const rootReal = await fs.realpath(root);
const targetReal = await fs.realpath(target);
return targetReal === rootReal || targetReal.startsWith(rootReal + path.sep);
}
// Pre-mkdir check: walk up from targetDir to find the first existing ancestor and verify
// its realpath is inside root. Prevents mkdir from creating directories outside the workspace
// when an intermediate component is a symlink pointing outside.
async function assertCreatableInside(root, targetDir) {
let rootReal;
try { rootReal = await fs.realpath(root); } catch { return; }
let cur = path.resolve(targetDir);
while (true) {
try {
const real = await fs.realpath(cur);
if (real !== rootReal && !real.startsWith(rootReal + path.sep)) {
throw new Error(`Refusing to write artifact through symlink outside workspace: ${targetDir}`);
}
return;
} catch (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
const parent = path.dirname(cur);
if (parent === cur) return;
cur = parent;
continue;
}
throw err;
}
}
}
async function writeArtifact(workDir, relDir, relFile, content) {
if (path.isAbsolute(relDir) || path.isAbsolute(relFile)) {
throw new Error('Refusing to write artifact with absolute path');
}
const root = path.resolve(workDir);
const dir = path.resolve(root, relDir);
const file = path.resolve(dir, relFile);
if (!safeInside(root, dir) || !safeInside(root, file)) {
throw new Error(`Refusing to write artifact outside workspace: ${file}`);
}
await assertCreatableInside(root, dir);
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
if (!(await safeInsideReal(root, dir))) {
throw new Error(`Refusing to write artifact through symlink outside workspace: ${dir}`);
}
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
await fs.writeFile(tmp, content, { mode: 0o600 });
await fs.rename(tmp, file);
return file;
}
function frontmatter(meta) {
return [
'---',
...Object.entries(meta)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => `${k}: ${JSON.stringify(v)}`),
'---',
'',
].join('\n');
}
function roundRelDir(artifactDir, runId, groupName, turn) {
const round = `round-${String(turn).padStart(3, '0')}`;
return path.join(artifactDir, slug(runId), slug(groupName), round);
}
async function writeManifest(workDir, artifactDir, runId, manifest) {
return writeArtifact(
workDir,
path.join(artifactDir, slug(runId)),
'manifest.json',
JSON.stringify(manifest, null, 2) + '\n',
);
}
async function writeInputPrompt(workDir, artifactDir, runId, text, meta = {}) {
return writeArtifact(
workDir,
path.join(artifactDir, slug(runId)),
'input-prompt.md',
frontmatter({
runId,
sessionId: meta.sessionId || runId,
promptId: meta.promptId,
group: meta.group,
status: 'input',
createdAt: new Date().toISOString(),
}) + `${text || ''}\n`,
);
}
async function writeRoundReports(workDir, artifactDir, runId, groupName, turn, results, meta = {}) {
const relDir = roundRelDir(artifactDir, runId, groupName, turn);
const written = [];
for (const [i, result] of results.entries()) {
const name = result.name || `agent-${i + 1}`;
const file = `${String(i + 1).padStart(2, '0')}-${slug(name)}.md`;
const body = result.error
? `FAILED: ${result.error}\n`
: `${result.result || ''}\n`;
const content = frontmatter({
runId,
sessionId: meta.sessionId || runId,
promptId: meta.promptId,
group: groupName,
round: turn,
agent: name,
status: result.error ? 'rejected' : 'fulfilled',
createdAt: new Date().toISOString(),
}) + body;
written.push(await writeArtifact(workDir, relDir, file, content));
}
return written;
}
async function writeReviewerReport(workDir, artifactDir, runId, groupName, turn, reviewerName, text, meta = {}) {
const relDir = roundRelDir(artifactDir, runId, groupName, turn);
return writeArtifact(
workDir,
relDir,
'reviewer.md',
frontmatter({
runId,
sessionId: meta.sessionId || runId,
promptId: meta.promptId,
group: groupName,
round: turn,
agent: reviewerName,
status: 'fulfilled',
createdAt: new Date().toISOString(),
}) + `${text || ''}\n`,
);
}
async function writeReviewerPrompt(workDir, artifactDir, runId, groupName, turn, text, meta = {}) {
const relDir = roundRelDir(artifactDir, runId, groupName, turn);
return writeArtifact(
workDir,
relDir,
'reviewer-prompt.md',
frontmatter({
runId,
sessionId: meta.sessionId || runId,
promptId: meta.promptId,
group: groupName,
round: turn,
status: 'reviewer_prompt',
createdAt: new Date().toISOString(),
}) + `${text || ''}\n`,
);
}
async function writeApprovedPlan(workDir, artifactDir, runId, groupName, text, meta = {}) {
return writeArtifact(
workDir,
path.join(artifactDir, slug(runId)),
'approved-plan.md',
frontmatter({
runId,
sessionId: meta.sessionId || runId,
promptId: meta.promptId,
group: groupName,
status: 'approved',
sha256: meta.sha256,
createdAt: new Date().toISOString(),
}) + `${text || ''}\n`,
);
}
async function writeApprovedPlanIndex(workDir, artifactDir, sessionId, planMeta) {
const relFile = 'index.json';
const root = path.resolve(workDir, artifactDir);
const file = path.resolve(root, relFile);
let index = { latestApprovedBySession: {} };
try {
if (safeInside(root, file)) {
const stat = await fs.lstat(file);
// Never follow a symlinked index while reading. writeArtifact() will later
// replace the symlink with a regular file inside the workspace, but the
// read side must not copy JSON from outside the artifact root.
if (stat.isFile() && await safeInsideReal(root, file)) {
const existing = await fs.readFile(file, 'utf8');
const parsed = JSON.parse(existing);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
index = {
latestApprovedBySession: parsed.latestApprovedBySession || {},
};
}
}
}
} catch {}
index.latestApprovedBySession[sessionId] = {
path: path.relative(path.resolve(workDir), planMeta.path),
sha256: planMeta.sha256,
group: planMeta.group,
createdAt: planMeta.createdAt,
};
return writeArtifact(
workDir,
artifactDir,
relFile,
JSON.stringify(index, null, 2) + '\n',
);
}
module.exports = {
slug,
safeInside,
safeInsideReal,
writeArtifact,
writeManifest,
writeInputPrompt,
writeRoundReports,
writeReviewerPrompt,
writeReviewerReport,
writeApprovedPlan,
writeApprovedPlanIndex,
};