@edjbarron/ux-guard 0.6.1 → 0.7.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.
- package/README.md +264 -104
- package/docs/cli-reference.md +38 -0
- package/docs/scoring-and-backslide.md +40 -0
- package/docs/test-suite.md +69 -2
- package/docs/use-case-review-design.md +284 -0
- package/docs/use-case-review.md +368 -0
- package/lib/catalog.mjs +46 -7
- package/lib/cli.mjs +288 -46
- package/lib/config.mjs +36 -1
- package/lib/review-app/app.css +697 -0
- package/lib/review-app/app.js +1899 -0
- package/lib/review-app/index.html +44 -0
- package/lib/review-audit.mjs +514 -0
- package/lib/review-command.mjs +409 -0
- package/lib/review-server.mjs +233 -0
- package/lib/review-store.mjs +554 -0
- package/lib/review.mjs +1385 -0
- package/lib/run-contract.mjs +1 -1
- package/package.json +1 -1
- package/skills/ux-guard/SKILL.md +131 -1
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import {
|
|
4
|
+
constants,
|
|
5
|
+
copyFileSync,
|
|
6
|
+
existsSync,
|
|
7
|
+
linkSync,
|
|
8
|
+
lstatSync,
|
|
9
|
+
readFileSync,
|
|
10
|
+
renameSync,
|
|
11
|
+
unlinkSync,
|
|
12
|
+
writeFileSync,
|
|
13
|
+
} from 'node:fs';
|
|
14
|
+
import { basename, dirname, join } from 'node:path';
|
|
15
|
+
import { navSurfaces } from './catalog.mjs';
|
|
16
|
+
import {
|
|
17
|
+
CONFIG_FILE,
|
|
18
|
+
assertRepositoryRelativePath,
|
|
19
|
+
ensureLocalDirectory,
|
|
20
|
+
loadConfig,
|
|
21
|
+
loadTypeScript,
|
|
22
|
+
resolveExistingRepositoryPath,
|
|
23
|
+
resolveRepositoryPath,
|
|
24
|
+
} from './config.mjs';
|
|
25
|
+
import {
|
|
26
|
+
PREVIEW_MARKER,
|
|
27
|
+
ReviewError,
|
|
28
|
+
candidateInputPaths,
|
|
29
|
+
computeReview,
|
|
30
|
+
definitionQuestion,
|
|
31
|
+
emptyReview,
|
|
32
|
+
parseUseCaseCandidate,
|
|
33
|
+
previewText,
|
|
34
|
+
reviewSubjects,
|
|
35
|
+
serializeReview,
|
|
36
|
+
stampCandidate,
|
|
37
|
+
useCaseCompleteness,
|
|
38
|
+
validateReviewDecisionCompleteness,
|
|
39
|
+
validateUseCaseReview,
|
|
40
|
+
} from './review.mjs';
|
|
41
|
+
import { sha256 } from './run-contract.mjs';
|
|
42
|
+
|
|
43
|
+
export const DEFAULT_REVIEW_PATHS = Object.freeze({
|
|
44
|
+
draft: 'ux-guard/use-case-draft.json',
|
|
45
|
+
candidate: 'ux-guard/use-case-candidate.json',
|
|
46
|
+
review: 'ux-guard/use-case-review.json',
|
|
47
|
+
preview: 'ux-guard/use-case-catalog.preview.yml',
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const MAX_ARTIFACT_BYTES = 16 * 1024 * 1024;
|
|
51
|
+
|
|
52
|
+
export class ReviewConflictError extends ReviewError {
|
|
53
|
+
constructor(message) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = 'ReviewConflictError';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function repositoryIdentity(root) {
|
|
60
|
+
const git = (args) =>
|
|
61
|
+
execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
62
|
+
try {
|
|
63
|
+
const commit = git(['rev-parse', '--verify', 'HEAD^{commit}']);
|
|
64
|
+
const rootCommits = git(['rev-list', '--max-parents=0', 'HEAD']).split(/\s+/).filter(Boolean).sort();
|
|
65
|
+
return { commit, rootCommits };
|
|
66
|
+
} catch {
|
|
67
|
+
return { commit: null, rootCommits: [] };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function hashInputs(root, paths) {
|
|
72
|
+
return [...new Set(paths)].sort().map((path) => {
|
|
73
|
+
const file = readRepositoryFile(root, path, `assessed input ${path}`);
|
|
74
|
+
if (!file) throw new ReviewError(`assessed input ${path} does not exist`);
|
|
75
|
+
return { path, sha256: file.sha256 };
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// candidateIdentity compares a stamped candidate with the current checkout.
|
|
80
|
+
// Changed or missing inputs make the candidate stale; a moved HEAD alone does
|
|
81
|
+
// not, because the assessed files are unchanged.
|
|
82
|
+
export function candidateIdentity(root, candidate) {
|
|
83
|
+
const current = repositoryIdentity(root);
|
|
84
|
+
const reasons = [];
|
|
85
|
+
const recorded = candidate.source.repository.rootCommits;
|
|
86
|
+
if (recorded.length && current.rootCommits.length && !recorded.some((id) => current.rootCommits.includes(id))) {
|
|
87
|
+
reasons.push('it was assessed in a different repository.');
|
|
88
|
+
}
|
|
89
|
+
if (recorded.length && current.rootCommits.length === 0) {
|
|
90
|
+
reasons.push('the repository identity it recorded cannot be verified here.');
|
|
91
|
+
}
|
|
92
|
+
for (const input of candidate.source.inputs) {
|
|
93
|
+
let file;
|
|
94
|
+
try {
|
|
95
|
+
file = readRepositoryFile(root, input.path, `assessed input ${input.path}`);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
reasons.push(`${input.path} cannot be read safely (${error.message}).`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (!file) reasons.push(`${input.path} no longer exists.`);
|
|
101
|
+
else if (file.sha256 !== input.sha256) reasons.push(`${input.path} changed after the assessment.`);
|
|
102
|
+
}
|
|
103
|
+
let status = 'current';
|
|
104
|
+
if (reasons.length) status = 'stale';
|
|
105
|
+
else if (!recorded.length && !current.rootCommits.length) status = 'unverified';
|
|
106
|
+
else if (candidate.source.commit !== current.commit) status = 'moved';
|
|
107
|
+
return {
|
|
108
|
+
status,
|
|
109
|
+
reasons,
|
|
110
|
+
candidateCommit: candidate.source.commit,
|
|
111
|
+
currentCommit: current.commit,
|
|
112
|
+
inputs: candidate.source.inputs.length,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// readRepositoryFile returns null for a missing file and rejects anything that
|
|
117
|
+
// is not a regular repository file reached through real directories.
|
|
118
|
+
export function readRepositoryFile(root, path, label) {
|
|
119
|
+
const full = resolveRepositoryPath(root, path, label);
|
|
120
|
+
if (!existsSync(full)) {
|
|
121
|
+
try {
|
|
122
|
+
lstatSync(full);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
ensureLocalDirectory(root, dirname(full), label, false);
|
|
128
|
+
const stats = lstatSync(full);
|
|
129
|
+
if (stats.isSymbolicLink() || !stats.isFile()) {
|
|
130
|
+
throw new ReviewError(`${label} must be a regular repository file, not a symbolic link`);
|
|
131
|
+
}
|
|
132
|
+
if (stats.size > MAX_ARTIFACT_BYTES) throw new ReviewError(`${label} is larger than 16 MiB`);
|
|
133
|
+
resolveExistingRepositoryPath(root, path, label);
|
|
134
|
+
const bytes = readFileSync(full);
|
|
135
|
+
return { text: bytes.toString('utf8'), sha256: sha256(bytes.toString('utf8')) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// writeNewFile never replaces an existing path: the content is written to a
|
|
139
|
+
// private temporary file and then hard-linked into place, which fails if the
|
|
140
|
+
// destination appeared in the meantime.
|
|
141
|
+
export function writeNewFile(root, path, text, label) {
|
|
142
|
+
const full = resolveRepositoryPath(root, path, `${label} path`);
|
|
143
|
+
ensureLocalDirectory(root, dirname(full), `${label} path`, true);
|
|
144
|
+
const temporary = temporaryPath(full);
|
|
145
|
+
writeFileSync(temporary, text, { flag: 'wx' });
|
|
146
|
+
try {
|
|
147
|
+
try {
|
|
148
|
+
linkSync(temporary, full);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error?.code === 'EEXIST') throw error;
|
|
151
|
+
copyFileSync(temporary, full, constants.COPYFILE_EXCL);
|
|
152
|
+
}
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error?.code === 'EEXIST') throw new ReviewConflictError(`${path} already exists; refusing to overwrite it`);
|
|
155
|
+
throw new ReviewError(`${label} ${path} could not be written`);
|
|
156
|
+
} finally {
|
|
157
|
+
safeUnlink(temporary);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// replaceFile swaps in new content only when the current file still has the
|
|
162
|
+
// content the caller last read.
|
|
163
|
+
export function replaceFile(root, path, text, expectedSha256, label) {
|
|
164
|
+
const full = resolveRepositoryPath(root, path, `${label} path`);
|
|
165
|
+
const current = readRepositoryFile(root, path, label);
|
|
166
|
+
if (!current) throw new ReviewConflictError(`${path} was removed after it was loaded; nothing was written`);
|
|
167
|
+
if (current.sha256 !== expectedSha256) {
|
|
168
|
+
throw new ReviewConflictError(`${path} changed after it was loaded; reload before saving so no edits are lost`);
|
|
169
|
+
}
|
|
170
|
+
const temporary = temporaryPath(full);
|
|
171
|
+
writeFileSync(temporary, text, { flag: 'wx' });
|
|
172
|
+
try {
|
|
173
|
+
const latest = readRepositoryFile(root, path, label);
|
|
174
|
+
if (latest?.sha256 !== expectedSha256) {
|
|
175
|
+
throw new ReviewConflictError(`${path} changed while saving; nothing was written`);
|
|
176
|
+
}
|
|
177
|
+
renameSync(temporary, full);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if (error instanceof ReviewError) throw error;
|
|
180
|
+
throw new ReviewError(`${label} ${path} could not be written`);
|
|
181
|
+
} finally {
|
|
182
|
+
safeUnlink(temporary);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function temporaryPath(full) {
|
|
187
|
+
return join(dirname(full), `.${basename(full)}.${randomBytes(6).toString('hex')}.tmp`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function safeUnlink(path) {
|
|
191
|
+
try {
|
|
192
|
+
unlinkSync(path);
|
|
193
|
+
} catch {
|
|
194
|
+
// Already renamed or never created.
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function prepareCandidate(root, { draftPath, candidatePath }) {
|
|
199
|
+
assertRepositoryRelativePath(draftPath, 'draft path');
|
|
200
|
+
assertRepositoryRelativePath(candidatePath, 'candidate path');
|
|
201
|
+
if (draftPath === candidatePath) throw new ReviewError('draft and candidate paths must differ');
|
|
202
|
+
if (candidatePath === CONFIG_FILE) throw new ReviewError(`candidate path cannot be ${CONFIG_FILE}`);
|
|
203
|
+
const draftFile = readRepositoryFile(root, draftPath, 'draft');
|
|
204
|
+
if (!draftFile) throw new ReviewError(`draft ${draftPath} does not exist`);
|
|
205
|
+
const parsedDraft = parseUseCaseCandidate(draftFile.text, { draft: true });
|
|
206
|
+
const draft = withDefinitionQuestions(parsedDraft);
|
|
207
|
+
const protectedPaths = policyPaths(root, draft.source.catalog);
|
|
208
|
+
if (protectedPaths.has(candidatePath)) {
|
|
209
|
+
throw new ReviewError(`candidate path ${candidatePath} is an active policy path`);
|
|
210
|
+
}
|
|
211
|
+
const identity = repositoryIdentity(root);
|
|
212
|
+
const inputs = hashInputs(root, candidateInputPaths({ ...draft, source: { ...draft.source } }));
|
|
213
|
+
const candidate = stampCandidate(draft, { ...identity, inputs });
|
|
214
|
+
writeNewFile(root, candidatePath, `${JSON.stringify(candidate, null, 2)}\n`, 'candidate');
|
|
215
|
+
const subjects = reviewSubjects(candidate, discoverSurfaces(root, navigationFiles(root, candidate)));
|
|
216
|
+
const incompleteDrafts = candidate.proposals
|
|
217
|
+
.filter(({ definitionStatus }) => definitionStatus === 'draft')
|
|
218
|
+
.map((proposal) => ({ id: proposal.id, ...useCaseCompleteness(proposal) }))
|
|
219
|
+
.map(({ id, missing, missingLabels }) => ({ id, missing, missingLabels }));
|
|
220
|
+
const completeProposals = candidate.proposals
|
|
221
|
+
.filter(({ definitionStatus }) => definitionStatus === 'proposal')
|
|
222
|
+
.map(({ id }) => id);
|
|
223
|
+
return {
|
|
224
|
+
candidate,
|
|
225
|
+
inputs: inputs.length,
|
|
226
|
+
completeProposals,
|
|
227
|
+
incompleteDrafts,
|
|
228
|
+
allDefinitionsIncomplete: candidate.proposals.length > 0 && completeProposals.length === 0,
|
|
229
|
+
notAssessed: subjects.filter(({ origin }) => origin === 'discovered').map(({ id, route }) => ({ id, route })),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function withDefinitionQuestions(draft) {
|
|
234
|
+
const questions = structuredClone(draft.questions);
|
|
235
|
+
const questionIds = new Set(questions.map(({ id }) => id));
|
|
236
|
+
const covered = new Set(
|
|
237
|
+
questions
|
|
238
|
+
.filter(({ useCaseId, missingFields }) => useCaseId && missingFields?.length)
|
|
239
|
+
.map(({ useCaseId }) => useCaseId),
|
|
240
|
+
);
|
|
241
|
+
for (const proposal of draft.proposals) {
|
|
242
|
+
if (proposal.definitionStatus !== 'draft' || covered.has(proposal.id)) continue;
|
|
243
|
+
const base = `${proposal.id}-definition`;
|
|
244
|
+
let id = base;
|
|
245
|
+
let suffix = 2;
|
|
246
|
+
while (questionIds.has(id)) {
|
|
247
|
+
id = `${base}-${suffix}`;
|
|
248
|
+
suffix += 1;
|
|
249
|
+
}
|
|
250
|
+
questions.push(definitionQuestion(proposal, id));
|
|
251
|
+
questionIds.add(id);
|
|
252
|
+
}
|
|
253
|
+
return { ...draft, questions };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// policyPaths lists files the review must never write: active configuration
|
|
257
|
+
// and every policy or evidence path it names.
|
|
258
|
+
function policyPaths(root, candidateCatalog) {
|
|
259
|
+
const paths = new Set([CONFIG_FILE, candidateCatalog]);
|
|
260
|
+
const config = activeConfig(root);
|
|
261
|
+
if (!config) return paths;
|
|
262
|
+
paths.add(config.catalog.path);
|
|
263
|
+
for (const path of config.catalog.navigation) paths.add(path);
|
|
264
|
+
paths.add(config.patterns.baseline);
|
|
265
|
+
for (const value of Object.values(config.journeys ?? {})) paths.add(value);
|
|
266
|
+
for (const value of Object.values(config.visuals ?? {})) paths.add(value);
|
|
267
|
+
return paths;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function activeConfig(root) {
|
|
271
|
+
return existsSync(join(root, CONFIG_FILE)) ? loadConfig(root, null) : null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function navigationFiles(root, candidate) {
|
|
275
|
+
return activeConfig(root)?.catalog.navigation ?? candidate.source.navigation;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function discoverSurfaces(root, files) {
|
|
279
|
+
let ts;
|
|
280
|
+
try {
|
|
281
|
+
ts = loadTypeScript();
|
|
282
|
+
} catch {
|
|
283
|
+
return [];
|
|
284
|
+
}
|
|
285
|
+
const surfaces = [];
|
|
286
|
+
for (const file of files) {
|
|
287
|
+
const source = readRepositoryFile(root, file, `navigation source ${file}`);
|
|
288
|
+
if (source) surfaces.push(...navSurfaces(ts, file, source.text));
|
|
289
|
+
}
|
|
290
|
+
return surfaces;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// loadReviewContext gathers everything the review needs from distinct paths.
|
|
294
|
+
// It returns { status: 'no-candidate' } only for the implicit default path.
|
|
295
|
+
export function loadReviewContext(root, { candidatePath, reviewPath, previewPath, explicitCandidate = false }) {
|
|
296
|
+
for (const [label, path] of [
|
|
297
|
+
['candidate path', candidatePath],
|
|
298
|
+
['review path', reviewPath],
|
|
299
|
+
['preview path', previewPath],
|
|
300
|
+
]) {
|
|
301
|
+
assertRepositoryRelativePath(path, label);
|
|
302
|
+
}
|
|
303
|
+
if (new Set([candidatePath, reviewPath, previewPath]).size !== 3) {
|
|
304
|
+
throw new ReviewError('candidate, review, and preview paths must all be different');
|
|
305
|
+
}
|
|
306
|
+
const candidateFile = readRepositoryFile(root, candidatePath, 'candidate');
|
|
307
|
+
if (!candidateFile) {
|
|
308
|
+
if (explicitCandidate) throw new ReviewError(`candidate ${candidatePath} does not exist`);
|
|
309
|
+
const draftFile = readRepositoryFile(root, DEFAULT_REVIEW_PATHS.draft, 'draft');
|
|
310
|
+
return { status: 'no-candidate', candidatePath, draftPresent: Boolean(draftFile) };
|
|
311
|
+
}
|
|
312
|
+
const candidate = parseUseCaseCandidate(candidateFile.text);
|
|
313
|
+
const config = activeConfig(root);
|
|
314
|
+
const protectedPaths = policyPaths(root, candidate.source.catalog);
|
|
315
|
+
for (const [label, path] of [
|
|
316
|
+
['candidate', candidatePath],
|
|
317
|
+
['review', reviewPath],
|
|
318
|
+
['preview', previewPath],
|
|
319
|
+
]) {
|
|
320
|
+
if (protectedPaths.has(path)) throw new ReviewError(`${label} path ${path} is an active policy path`);
|
|
321
|
+
}
|
|
322
|
+
const activeCatalog = readActiveCatalog(root, config, candidate);
|
|
323
|
+
const discoveredSurfaces = discoverSurfaces(root, navigationFiles(root, candidate));
|
|
324
|
+
const subjects = reviewSubjects(candidate, discoveredSurfaces);
|
|
325
|
+
const scope = {
|
|
326
|
+
proposalIds: candidate.proposals.map(({ id }) => id),
|
|
327
|
+
subjectKeys: subjects.map(({ key }) => key),
|
|
328
|
+
};
|
|
329
|
+
const reviewFile = readRepositoryFile(root, reviewPath, 'review');
|
|
330
|
+
let review;
|
|
331
|
+
if (reviewFile) {
|
|
332
|
+
let value;
|
|
333
|
+
try {
|
|
334
|
+
value = JSON.parse(reviewFile.text);
|
|
335
|
+
} catch {
|
|
336
|
+
throw new ReviewError(`review ${reviewPath} is not valid JSON`);
|
|
337
|
+
}
|
|
338
|
+
review = validateReviewDecisionCompleteness(candidate, validateUseCaseReview(value, scope));
|
|
339
|
+
if (review.candidate.path !== candidatePath || review.candidate.sha256 !== candidateFile.sha256) {
|
|
340
|
+
throw new ReviewError(
|
|
341
|
+
`review ${reviewPath} was recorded against a different candidate; open it with its original candidate or choose a new --review path`,
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
} else {
|
|
345
|
+
review = emptyReview(candidatePath, candidateFile.sha256);
|
|
346
|
+
}
|
|
347
|
+
return {
|
|
348
|
+
status: 'ready',
|
|
349
|
+
root,
|
|
350
|
+
candidatePath,
|
|
351
|
+
reviewPath,
|
|
352
|
+
previewPath,
|
|
353
|
+
candidate,
|
|
354
|
+
candidateSha256: candidateFile.sha256,
|
|
355
|
+
review,
|
|
356
|
+
reviewSha256: reviewFile?.sha256 ?? null,
|
|
357
|
+
scope,
|
|
358
|
+
activeCatalog,
|
|
359
|
+
discoveredSurfaces,
|
|
360
|
+
identity: candidateIdentity(root, candidate),
|
|
361
|
+
configured: Boolean(config),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function readActiveCatalog(root, config, candidate) {
|
|
366
|
+
if (config) {
|
|
367
|
+
const file = readRepositoryFile(root, config.catalog.path, `catalog ${config.catalog.path}`);
|
|
368
|
+
return {
|
|
369
|
+
path: config.catalog.path,
|
|
370
|
+
origin: 'config',
|
|
371
|
+
text: file?.text ?? null,
|
|
372
|
+
mismatch:
|
|
373
|
+
candidate.source.catalog === config.catalog.path
|
|
374
|
+
? null
|
|
375
|
+
: `The candidate names ${candidate.source.catalog}, but active policy uses ${config.catalog.path}; the review uses active policy.`,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
const file = readRepositoryFile(root, candidate.source.catalog, `catalog ${candidate.source.catalog}`);
|
|
379
|
+
return { path: candidate.source.catalog, origin: 'candidate', text: file?.text ?? null, mismatch: null };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// refreshContext re-reads the inputs that can change while the app is open so
|
|
383
|
+
// staleness and the catalog diff never reflect an earlier checkout.
|
|
384
|
+
export function refreshContext(context) {
|
|
385
|
+
context.identity = candidateIdentity(context.root, context.candidate);
|
|
386
|
+
context.activeCatalog = readActiveCatalog(
|
|
387
|
+
context.root,
|
|
388
|
+
context.configured ? loadConfig(context.root, null) : null,
|
|
389
|
+
context.candidate,
|
|
390
|
+
);
|
|
391
|
+
return context;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export function evaluateReview(context, review = context.review) {
|
|
395
|
+
return computeReview({
|
|
396
|
+
candidate: context.candidate,
|
|
397
|
+
review,
|
|
398
|
+
activeCatalog: context.activeCatalog,
|
|
399
|
+
discoveredSurfaces: context.discoveredSurfaces,
|
|
400
|
+
identity: context.identity,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function parseReviewDraft(context, value) {
|
|
405
|
+
const review = validateReviewDecisionCompleteness(
|
|
406
|
+
context.candidate,
|
|
407
|
+
validateUseCaseReview(value, context.scope),
|
|
408
|
+
);
|
|
409
|
+
if (review.candidate.path !== context.candidatePath || review.candidate.sha256 !== context.candidateSha256) {
|
|
410
|
+
throw new ReviewError('review decisions belong to a different candidate');
|
|
411
|
+
}
|
|
412
|
+
return review;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// saveReview writes only the review artifact and its generated preview. The
|
|
416
|
+
// expected hash guards against overwriting a concurrent edit.
|
|
417
|
+
export function saveReview(context, value) {
|
|
418
|
+
const review = parseReviewDraft(context, value);
|
|
419
|
+
if (review.revision !== context.review.revision) {
|
|
420
|
+
throw new ReviewConflictError(
|
|
421
|
+
`review revision ${review.revision} is not the loaded revision ${context.review.revision}; reload before saving`,
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
const next = { ...review, revision: review.revision + 1 };
|
|
425
|
+
const state = evaluateReview(context, next);
|
|
426
|
+
const text = serializeReview(next);
|
|
427
|
+
if (context.reviewSha256 === null) writeNewFile(context.root, context.reviewPath, text, 'review');
|
|
428
|
+
else replaceFile(context.root, context.reviewPath, text, context.reviewSha256, 'review');
|
|
429
|
+
context.review = next;
|
|
430
|
+
context.reviewSha256 = sha256(text);
|
|
431
|
+
const preview =
|
|
432
|
+
previewText(state) ??
|
|
433
|
+
`${PREVIEW_MARKER}\n# No use cases can be generated yet; resolve the blocking review items.\n`;
|
|
434
|
+
const existing = readRepositoryFile(context.root, context.previewPath, 'preview');
|
|
435
|
+
if (!existing) writeNewFile(context.root, context.previewPath, preview, 'preview');
|
|
436
|
+
else if (!existing.text.startsWith(`${PREVIEW_MARKER}\n`)) {
|
|
437
|
+
throw new ReviewConflictError(
|
|
438
|
+
`${context.previewPath} is not a generated ux-guard preview; the review was saved but the preview was not written`,
|
|
439
|
+
);
|
|
440
|
+
} else if (existing.text !== preview) {
|
|
441
|
+
replaceFile(context.root, context.previewPath, preview, existing.sha256, 'preview');
|
|
442
|
+
}
|
|
443
|
+
return { state, revision: next.revision, reviewSha256: context.reviewSha256 };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// adoptionCommand is shown to the owner, never run by the app.
|
|
447
|
+
export function adoptionCommand(context, state) {
|
|
448
|
+
const quote = (value) => (/^[A-Za-z0-9_./@-]+$/.test(value) ? value : `"${value}"`);
|
|
449
|
+
const parts = ['npx ux-guard review adopt'];
|
|
450
|
+
for (const [option, value, fallback] of [
|
|
451
|
+
['--candidate', context.candidatePath, DEFAULT_REVIEW_PATHS.candidate],
|
|
452
|
+
['--review', context.reviewPath, DEFAULT_REVIEW_PATHS.review],
|
|
453
|
+
['--preview', context.previewPath, DEFAULT_REVIEW_PATHS.preview],
|
|
454
|
+
]) {
|
|
455
|
+
if (value !== fallback) parts.push(`${option} ${quote(value)}`);
|
|
456
|
+
}
|
|
457
|
+
if (!context.configured) parts.push(`--catalog ${quote(state.catalog.path)}`);
|
|
458
|
+
if (state.catalog.exists) parts.push(`--replace-catalog-sha256 ${state.catalog.activeSha256}`);
|
|
459
|
+
parts.push('--reviewer "<owner>"', '--reviewed-at "<UTC time>"', '--rationale "<why the owner approves>"');
|
|
460
|
+
return parts.join(' ');
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
|
|
464
|
+
|
|
465
|
+
// adoptReview is the only path that writes the active catalog. It requires a
|
|
466
|
+
// saved, current, conflict-free review whose saved preview matches exactly.
|
|
467
|
+
export function adoptReview(context, { reviewer, reviewedAt, rationale, catalogPath, replaceSha256 }) {
|
|
468
|
+
for (const [name, value] of [
|
|
469
|
+
['--reviewer', reviewer],
|
|
470
|
+
['--reviewed-at', reviewedAt],
|
|
471
|
+
['--rationale', rationale],
|
|
472
|
+
]) {
|
|
473
|
+
if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value)) {
|
|
474
|
+
throw new ReviewError(`review adopt requires a single-line ${name}`);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (!UTC.test(reviewedAt) || Number.isNaN(Date.parse(reviewedAt))) {
|
|
478
|
+
throw new ReviewError('--reviewed-at must be a UTC timestamp like 2026-01-31T12:00:00Z');
|
|
479
|
+
}
|
|
480
|
+
if (context.reviewSha256 === null) {
|
|
481
|
+
throw new ReviewError(`review ${context.reviewPath} has not been saved; save the review before adoption`);
|
|
482
|
+
}
|
|
483
|
+
if (context.identity.status === 'stale') {
|
|
484
|
+
throw new ReviewError(`candidate is stale: ${context.identity.reasons.join(' ')} Prepare a fresh candidate and review it.`);
|
|
485
|
+
}
|
|
486
|
+
const state = evaluateReview(context);
|
|
487
|
+
if (state.summary.blockingIssues > 0) {
|
|
488
|
+
const first = state.issues.find(({ severity }) => severity === 'error');
|
|
489
|
+
throw new ReviewError(
|
|
490
|
+
`review has ${state.summary.blockingIssues} blocking issue(s); resolve them before adoption. First: ${first.message}`,
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
const expectedPreview = previewText(state);
|
|
494
|
+
const preview = readRepositoryFile(context.root, context.previewPath, 'preview');
|
|
495
|
+
if (!preview || preview.text !== expectedPreview) {
|
|
496
|
+
throw new ReviewError(
|
|
497
|
+
`${context.previewPath} does not match the saved review; reopen the review, check the diff, and save again`,
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
let target;
|
|
501
|
+
if (context.configured) {
|
|
502
|
+
target = context.activeCatalog.path;
|
|
503
|
+
if (catalogPath && catalogPath !== target) {
|
|
504
|
+
throw new ReviewError(`--catalog ${catalogPath} differs from active policy catalog ${target}`);
|
|
505
|
+
}
|
|
506
|
+
} else {
|
|
507
|
+
if (!catalogPath) {
|
|
508
|
+
throw new ReviewError(
|
|
509
|
+
`no active ux-guard policy names a catalog; pass --catalog <path> to choose where the owner-approved catalog is written`,
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
target = assertRepositoryRelativePath(catalogPath, '--catalog');
|
|
513
|
+
}
|
|
514
|
+
if ([CONFIG_FILE, context.candidatePath, context.reviewPath, context.previewPath].includes(target)) {
|
|
515
|
+
throw new ReviewError(`--catalog cannot be ${target}`);
|
|
516
|
+
}
|
|
517
|
+
const current = readRepositoryFile(context.root, target, `catalog ${target}`);
|
|
518
|
+
if (current) {
|
|
519
|
+
if (!replaceSha256) {
|
|
520
|
+
throw new ReviewError(
|
|
521
|
+
`${target} exists; pass --replace-catalog-sha256 ${current.sha256} to confirm replacing exactly this file`,
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
replaceFile(context.root, target, state.catalog.text, replaceSha256, 'catalog');
|
|
525
|
+
} else {
|
|
526
|
+
if (replaceSha256) throw new ReviewError(`${target} does not exist; omit --replace-catalog-sha256`);
|
|
527
|
+
writeNewFile(context.root, target, state.catalog.text, 'catalog');
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
kind: 'ux-guard-use-case-adoption',
|
|
531
|
+
version: 1,
|
|
532
|
+
status: state.summary.unresolvedDecisions ? 'adopted-with-unresolved-items' : 'adopted',
|
|
533
|
+
catalog: {
|
|
534
|
+
path: target,
|
|
535
|
+
previousSha256: current?.sha256 ?? null,
|
|
536
|
+
sha256: sha256(state.catalog.text),
|
|
537
|
+
inventory: state.catalog.inventory,
|
|
538
|
+
useCases: state.catalog.entries,
|
|
539
|
+
},
|
|
540
|
+
approval: { reviewer, reviewedAt, rationale },
|
|
541
|
+
review: { path: context.reviewPath, sha256: context.reviewSha256, revision: context.review.revision },
|
|
542
|
+
candidate: { path: context.candidatePath, sha256: context.candidateSha256, identity: context.identity.status },
|
|
543
|
+
unresolved: state.unresolved,
|
|
544
|
+
unchanged: {
|
|
545
|
+
configuration: true,
|
|
546
|
+
baselines: true,
|
|
547
|
+
targets: true,
|
|
548
|
+
waivers: true,
|
|
549
|
+
enforcement: true,
|
|
550
|
+
},
|
|
551
|
+
nextAction:
|
|
552
|
+
'Review the catalog change, then decide separately whether to check it in and whether to change enforcement.',
|
|
553
|
+
};
|
|
554
|
+
}
|