@edjbarron/ux-guard 0.6.0 → 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 +304 -58
- package/docs/cli-reference.md +92 -7
- package/docs/scoring-and-backslide.md +140 -0
- package/docs/test-suite.md +72 -5
- 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 +368 -84
- 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 +154 -12
package/lib/review.mjs
ADDED
|
@@ -0,0 +1,1385 @@
|
|
|
1
|
+
import { isCanonicalDirectRoute, validateCatalog } from './catalog.mjs';
|
|
2
|
+
import { assertRepositoryRelativePath } from './config.mjs';
|
|
3
|
+
import { canonicalize, sha256 } from './run-contract.mjs';
|
|
4
|
+
import { ConfigError, parseYamlSubset } from './yaml.mjs';
|
|
5
|
+
|
|
6
|
+
export const USE_CASE_DRAFT_KIND = 'ux-guard-use-case-draft';
|
|
7
|
+
export const USE_CASE_CANDIDATE_KIND = 'ux-guard-use-case-candidate';
|
|
8
|
+
export const USE_CASE_REVIEW_KIND = 'ux-guard-use-case-review';
|
|
9
|
+
export const USE_CASE_REVIEW_VERSION = 1;
|
|
10
|
+
export const PREVIEW_MARKER =
|
|
11
|
+
'# ux-guard use-case catalog preview: generated, unapproved, and not active policy.';
|
|
12
|
+
|
|
13
|
+
const USE_CASE_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
14
|
+
const SUBJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
|
|
15
|
+
const COMMIT = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
16
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
17
|
+
const TIERS = ['primary', 'secondary', 'tertiary'];
|
|
18
|
+
const EFFECTS = ['read', 'create', 'change'];
|
|
19
|
+
const CAPABILITIES = [
|
|
20
|
+
'present',
|
|
21
|
+
'partial',
|
|
22
|
+
'absent',
|
|
23
|
+
'deployment-dependent',
|
|
24
|
+
'not-applicable',
|
|
25
|
+
'unknown',
|
|
26
|
+
];
|
|
27
|
+
const DISPOSITIONS = ['existing-use-case', 'proposed-use-case', 'excluded', 'unresolved'];
|
|
28
|
+
const SURFACE_KINDS = ['destination', 'group', 'subtree', 'hidden', 'other'];
|
|
29
|
+
const ACTIONS = ['pending', 'approve', 'revise', 'reject', 'merge', 'split'];
|
|
30
|
+
const DEFINITION_STATUSES = ['proposal', 'draft'];
|
|
31
|
+
const MAPPING_DISPOSITIONS = ['use-case', 'excluded', 'unresolved'];
|
|
32
|
+
const TEXT_FIELDS = ['title', 'persona', 'goal', 'success', 'rationale'];
|
|
33
|
+
const EDITABLE_FIELDS = [...TEXT_FIELDS, 'tier', 'effect', 'outcome', 'starts', 'requirements', 'gaps'];
|
|
34
|
+
// Accept legacy owner metadata in existing candidates and reviews without
|
|
35
|
+
// making it part of use-case definition or exposing it as a review field.
|
|
36
|
+
const ACCEPTED_USE_CASE_FIELDS = [...EDITABLE_FIELDS, 'owner'];
|
|
37
|
+
const CATALOG_ORDER = [
|
|
38
|
+
'id',
|
|
39
|
+
'title',
|
|
40
|
+
'persona',
|
|
41
|
+
'tier',
|
|
42
|
+
'effect',
|
|
43
|
+
'owner',
|
|
44
|
+
'goal',
|
|
45
|
+
'success',
|
|
46
|
+
'starts',
|
|
47
|
+
'requirements',
|
|
48
|
+
'gaps',
|
|
49
|
+
];
|
|
50
|
+
const REQUIRED_FOR_CATALOG = ['title', 'persona', 'tier', 'effect', 'goal', 'success'];
|
|
51
|
+
const DEFINITION_LABELS = {
|
|
52
|
+
title: 'Title',
|
|
53
|
+
persona: 'Persona',
|
|
54
|
+
tier: 'Tier',
|
|
55
|
+
effect: 'Effect',
|
|
56
|
+
goal: 'Goal',
|
|
57
|
+
success: 'Success outcome',
|
|
58
|
+
};
|
|
59
|
+
const MAX_TEXT = 4000;
|
|
60
|
+
const MAX_ITEMS = 5000;
|
|
61
|
+
|
|
62
|
+
export class ReviewError extends ConfigError {
|
|
63
|
+
constructor(message) {
|
|
64
|
+
super(message);
|
|
65
|
+
this.name = 'ReviewError';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// validateUseCaseCandidate accepts an agent-authored draft or a stamped
|
|
70
|
+
// candidate. Only the CLI stamps repository identity, so a draft may not carry
|
|
71
|
+
// identity fields and a candidate must carry all of them.
|
|
72
|
+
export function validateUseCaseCandidate(value, { draft = false } = {}) {
|
|
73
|
+
const path = draft ? 'draft' : 'candidate';
|
|
74
|
+
assertMap(value, path);
|
|
75
|
+
assertKeys(
|
|
76
|
+
value,
|
|
77
|
+
['kind', 'version', 'approval', 'source', 'outcomes', 'proposals', 'surfaces', 'workflows', 'questions'],
|
|
78
|
+
['kind', 'version', 'approval', 'source'],
|
|
79
|
+
path,
|
|
80
|
+
);
|
|
81
|
+
const kind = draft ? USE_CASE_DRAFT_KIND : USE_CASE_CANDIDATE_KIND;
|
|
82
|
+
if (value.kind !== kind) throw new ReviewError(`${path}.kind must be ${kind}`);
|
|
83
|
+
if (value.version !== USE_CASE_REVIEW_VERSION) {
|
|
84
|
+
throw new ReviewError(`${path}.version must be ${USE_CASE_REVIEW_VERSION}`);
|
|
85
|
+
}
|
|
86
|
+
assertUnapproved(value.approval, `${path}.approval`);
|
|
87
|
+
const source = validateSource(value.source, `${path}.source`, draft);
|
|
88
|
+
const outcomes = list(value.outcomes, `${path}.outcomes`).map((item, index) =>
|
|
89
|
+
validateOutcome(item, `${path}.outcomes[${index}]`),
|
|
90
|
+
);
|
|
91
|
+
uniqueIds(outcomes, `${path}.outcomes`);
|
|
92
|
+
const outcomeIds = new Set(outcomes.map(({ id }) => id));
|
|
93
|
+
const proposals = list(value.proposals, `${path}.proposals`).map((item, index) => {
|
|
94
|
+
const itemPath = `${path}.proposals[${index}]`;
|
|
95
|
+
assertMap(item, itemPath);
|
|
96
|
+
assertKeys(
|
|
97
|
+
item,
|
|
98
|
+
['id', 'definitionStatus', ...ACCEPTED_USE_CASE_FIELDS, 'capability'],
|
|
99
|
+
['id', 'title'],
|
|
100
|
+
itemPath,
|
|
101
|
+
);
|
|
102
|
+
const fields = validateUseCaseFields(
|
|
103
|
+
omit(item, ['id', 'definitionStatus', 'capability']),
|
|
104
|
+
itemPath,
|
|
105
|
+
);
|
|
106
|
+
const completeness = useCaseCompleteness(fields);
|
|
107
|
+
const inferredStatus = completeness.complete ? 'proposal' : 'draft';
|
|
108
|
+
const definitionStatus =
|
|
109
|
+
item.definitionStatus === undefined
|
|
110
|
+
? inferredStatus
|
|
111
|
+
: oneOf(item.definitionStatus, DEFINITION_STATUSES, `${itemPath}.definitionStatus`);
|
|
112
|
+
if (definitionStatus !== inferredStatus) {
|
|
113
|
+
throw new ReviewError(
|
|
114
|
+
`${itemPath}.definitionStatus is ${definitionStatus}, but its definition fields make it a ${inferredStatus}`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
const proposal = {
|
|
118
|
+
id: useCaseId(item.id, `${itemPath}.id`),
|
|
119
|
+
definitionStatus,
|
|
120
|
+
...fields,
|
|
121
|
+
};
|
|
122
|
+
if (item.capability !== undefined) proposal.capability = oneOf(item.capability, CAPABILITIES, `${itemPath}.capability`);
|
|
123
|
+
if (proposal.outcome && !outcomeIds.has(proposal.outcome)) {
|
|
124
|
+
throw new ReviewError(`${itemPath}.outcome names unknown outcome ${proposal.outcome}`);
|
|
125
|
+
}
|
|
126
|
+
return proposal;
|
|
127
|
+
});
|
|
128
|
+
uniqueIds(proposals, `${path}.proposals`);
|
|
129
|
+
const surfaces = list(value.surfaces, `${path}.surfaces`).map((item, index) =>
|
|
130
|
+
validateSubject(item, `${path}.surfaces[${index}]`, 'surface'),
|
|
131
|
+
);
|
|
132
|
+
uniqueIds(surfaces, `${path}.surfaces`);
|
|
133
|
+
const workflows = list(value.workflows, `${path}.workflows`).map((item, index) =>
|
|
134
|
+
validateSubject(item, `${path}.workflows[${index}]`, 'workflow'),
|
|
135
|
+
);
|
|
136
|
+
uniqueIds(workflows, `${path}.workflows`);
|
|
137
|
+
const proposalIds = new Set(proposals.map(({ id }) => id));
|
|
138
|
+
const proposalsById = new Map(proposals.map((proposal) => [proposal.id, proposal]));
|
|
139
|
+
const questions = list(value.questions, `${path}.questions`).map((item, index) => {
|
|
140
|
+
const itemPath = `${path}.questions[${index}]`;
|
|
141
|
+
assertMap(item, itemPath);
|
|
142
|
+
assertKeys(
|
|
143
|
+
item,
|
|
144
|
+
['id', 'question', 'impact', 'useCaseId', 'missingFields'],
|
|
145
|
+
['id', 'question'],
|
|
146
|
+
itemPath,
|
|
147
|
+
);
|
|
148
|
+
const question = { id: subjectId(item.id, `${itemPath}.id`), question: text(item.question, `${itemPath}.question`) };
|
|
149
|
+
if (item.impact !== undefined) question.impact = text(item.impact, `${itemPath}.impact`, true);
|
|
150
|
+
if (item.useCaseId !== undefined || item.missingFields !== undefined) {
|
|
151
|
+
if (item.useCaseId === undefined || item.missingFields === undefined) {
|
|
152
|
+
throw new ReviewError(`${itemPath}.useCaseId and missingFields must be provided together`);
|
|
153
|
+
}
|
|
154
|
+
question.useCaseId = useCaseId(item.useCaseId, `${itemPath}.useCaseId`);
|
|
155
|
+
if (!proposalIds.has(question.useCaseId)) {
|
|
156
|
+
throw new ReviewError(`${itemPath}.useCaseId names unknown use case ${question.useCaseId}`);
|
|
157
|
+
}
|
|
158
|
+
question.missingFields = list(item.missingFields, `${itemPath}.missingFields`).map((field, fieldIndex) =>
|
|
159
|
+
oneOf(field, REQUIRED_FOR_CATALOG, `${itemPath}.missingFields[${fieldIndex}]`),
|
|
160
|
+
);
|
|
161
|
+
if (question.missingFields.length === 0 || new Set(question.missingFields).size !== question.missingFields.length) {
|
|
162
|
+
throw new ReviewError(`${itemPath}.missingFields must name one or more different definition fields`);
|
|
163
|
+
}
|
|
164
|
+
const missing = new Set(useCaseCompleteness(proposalsById.get(question.useCaseId)).missing);
|
|
165
|
+
const resolved = question.missingFields.find((field) => !missing.has(field));
|
|
166
|
+
if (resolved) {
|
|
167
|
+
throw new ReviewError(
|
|
168
|
+
`${itemPath}.missingFields names ${resolved}, but ${question.useCaseId} already provides it`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
if (
|
|
172
|
+
question.missingFields.length !== missing.size ||
|
|
173
|
+
[...missing].some((field) => !question.missingFields.includes(field))
|
|
174
|
+
) {
|
|
175
|
+
throw new ReviewError(
|
|
176
|
+
`${itemPath}.missingFields must exactly match the missing definition fields for ${question.useCaseId}`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return question;
|
|
181
|
+
});
|
|
182
|
+
uniqueIds(questions, `${path}.questions`);
|
|
183
|
+
if (proposals.length + surfaces.length + workflows.length === 0) {
|
|
184
|
+
throw new ReviewError(`${path} needs at least one proposal, surface, or workflow`);
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
kind,
|
|
188
|
+
version: USE_CASE_REVIEW_VERSION,
|
|
189
|
+
approval: { status: 'unapproved', activatesCatalog: false },
|
|
190
|
+
source,
|
|
191
|
+
outcomes,
|
|
192
|
+
proposals,
|
|
193
|
+
surfaces,
|
|
194
|
+
workflows,
|
|
195
|
+
questions,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function parseUseCaseCandidate(text, options = {}) {
|
|
200
|
+
let value;
|
|
201
|
+
try {
|
|
202
|
+
value = JSON.parse(text);
|
|
203
|
+
} catch {
|
|
204
|
+
throw new ReviewError(`${options.draft ? 'draft' : 'candidate'} is not valid JSON`);
|
|
205
|
+
}
|
|
206
|
+
return validateUseCaseCandidate(value, options);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// The stamped candidate keeps the draft's assessment and adds identity that
|
|
210
|
+
// only the CLI computes.
|
|
211
|
+
export function stampCandidate(draft, identity) {
|
|
212
|
+
const validated = validateUseCaseCandidate(draft, { draft: true });
|
|
213
|
+
return validateUseCaseCandidate({
|
|
214
|
+
...validated,
|
|
215
|
+
kind: USE_CASE_CANDIDATE_KIND,
|
|
216
|
+
source: {
|
|
217
|
+
repository: { rootCommits: identity.rootCommits },
|
|
218
|
+
commit: identity.commit,
|
|
219
|
+
catalog: validated.source.catalog,
|
|
220
|
+
navigation: validated.source.navigation,
|
|
221
|
+
inputs: identity.inputs,
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function candidateInputPaths(candidate) {
|
|
227
|
+
const paths = new Set(candidate.source.navigation);
|
|
228
|
+
for (const subject of [...candidate.surfaces, ...candidate.workflows]) {
|
|
229
|
+
for (const path of subject.sources) paths.add(path);
|
|
230
|
+
}
|
|
231
|
+
return [...paths].sort();
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function emptyReview(candidatePath, candidateSha256) {
|
|
235
|
+
return {
|
|
236
|
+
kind: USE_CASE_REVIEW_KIND,
|
|
237
|
+
version: USE_CASE_REVIEW_VERSION,
|
|
238
|
+
approval: { status: 'unapproved', activatesCatalog: false },
|
|
239
|
+
candidate: { path: candidatePath, sha256: candidateSha256 },
|
|
240
|
+
revision: 0,
|
|
241
|
+
proposals: {},
|
|
242
|
+
added: [],
|
|
243
|
+
mappings: {},
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function subjectKey(type, id) {
|
|
248
|
+
return `${type}:${id}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function useCaseCompleteness(value) {
|
|
252
|
+
const missing = REQUIRED_FOR_CATALOG.filter((field) => isBlank(value[field]));
|
|
253
|
+
return {
|
|
254
|
+
complete: missing.length === 0,
|
|
255
|
+
missing,
|
|
256
|
+
missingLabels: missing.map((field) => DEFINITION_LABELS[field]),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function definitionQuestion(proposal, id = `${proposal.id}-definition`) {
|
|
261
|
+
const completeness = useCaseCompleteness(proposal);
|
|
262
|
+
if (completeness.complete) return null;
|
|
263
|
+
const labels =
|
|
264
|
+
completeness.missingLabels.length === 1
|
|
265
|
+
? completeness.missingLabels[0]
|
|
266
|
+
: `${completeness.missingLabels.slice(0, -1).join(', ')} and ${completeness.missingLabels.at(-1)}`;
|
|
267
|
+
return {
|
|
268
|
+
id,
|
|
269
|
+
question: `What evidence-supported ${labels} should complete “${proposal.title}”?`,
|
|
270
|
+
impact: `Until answered, ${proposal.id} remains an incomplete draft and cannot be accepted as proposed.`,
|
|
271
|
+
useCaseId: proposal.id,
|
|
272
|
+
missingFields: completeness.missing,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// validateUseCaseReview checks structure strictly. Incomplete decisions are
|
|
277
|
+
// not errors here; computeReview reports them as unresolved.
|
|
278
|
+
export function validateUseCaseReview(value, { proposalIds, subjectKeys }) {
|
|
279
|
+
assertMap(value, 'review');
|
|
280
|
+
assertKeys(
|
|
281
|
+
value,
|
|
282
|
+
['kind', 'version', 'approval', 'candidate', 'revision', 'proposals', 'added', 'mappings'],
|
|
283
|
+
['kind', 'version', 'approval', 'candidate', 'revision', 'proposals', 'added', 'mappings'],
|
|
284
|
+
'review',
|
|
285
|
+
);
|
|
286
|
+
if (value.kind !== USE_CASE_REVIEW_KIND) throw new ReviewError(`review.kind must be ${USE_CASE_REVIEW_KIND}`);
|
|
287
|
+
if (value.version !== USE_CASE_REVIEW_VERSION) {
|
|
288
|
+
throw new ReviewError(`review.version must be ${USE_CASE_REVIEW_VERSION}`);
|
|
289
|
+
}
|
|
290
|
+
assertUnapproved(value.approval, 'review.approval');
|
|
291
|
+
assertMap(value.candidate, 'review.candidate');
|
|
292
|
+
assertKeys(value.candidate, ['path', 'sha256'], ['path', 'sha256'], 'review.candidate');
|
|
293
|
+
const candidate = {
|
|
294
|
+
path: repositoryPath(value.candidate.path, 'review.candidate.path'),
|
|
295
|
+
sha256: hash(value.candidate.sha256, 'review.candidate.sha256'),
|
|
296
|
+
};
|
|
297
|
+
if (!Number.isSafeInteger(value.revision) || value.revision < 0) {
|
|
298
|
+
throw new ReviewError('review.revision must be a non-negative integer');
|
|
299
|
+
}
|
|
300
|
+
const known = new Set(proposalIds);
|
|
301
|
+
const added = list(value.added, 'review.added').map((item, index) => {
|
|
302
|
+
const path = `review.added[${index}]`;
|
|
303
|
+
assertMap(item, path);
|
|
304
|
+
assertKeys(item, ['id', 'origin', 'from', ...ACCEPTED_USE_CASE_FIELDS], ['id', 'origin', 'title'], path);
|
|
305
|
+
const entry = {
|
|
306
|
+
id: useCaseId(item.id, `${path}.id`),
|
|
307
|
+
origin: oneOf(item.origin, ['added', 'split'], `${path}.origin`),
|
|
308
|
+
...validateUseCaseFields(omit(item, ['id', 'origin', 'from']), path),
|
|
309
|
+
};
|
|
310
|
+
if (entry.origin === 'split') {
|
|
311
|
+
entry.from = useCaseId(item.from, `${path}.from`);
|
|
312
|
+
if (!known.has(entry.from)) throw new ReviewError(`${path}.from names unknown proposal ${entry.from}`);
|
|
313
|
+
} else if (item.from !== undefined) {
|
|
314
|
+
throw new ReviewError(`${path}.from is only valid for split parts`);
|
|
315
|
+
}
|
|
316
|
+
if (known.has(entry.id)) throw new ReviewError(`${path}.id duplicates proposal ${entry.id}`);
|
|
317
|
+
return entry;
|
|
318
|
+
});
|
|
319
|
+
uniqueIds(added, 'review.added');
|
|
320
|
+
|
|
321
|
+
assertMap(value.proposals, 'review.proposals');
|
|
322
|
+
const proposals = {};
|
|
323
|
+
for (const id of Object.keys(value.proposals).sort()) {
|
|
324
|
+
const path = `review.proposals.${id}`;
|
|
325
|
+
if (!known.has(id)) throw new ReviewError(`${path} names an unknown proposal`);
|
|
326
|
+
const decision = value.proposals[id];
|
|
327
|
+
assertMap(decision, path);
|
|
328
|
+
const action = oneOf(decision.action, ACTIONS, `${path}.action`);
|
|
329
|
+
const allowed = {
|
|
330
|
+
pending: ['action', 'fields', 'note'],
|
|
331
|
+
approve: ['action', 'note'],
|
|
332
|
+
revise: ['action', 'fields', 'note'],
|
|
333
|
+
reject: ['action', 'note'],
|
|
334
|
+
merge: ['action', 'into', 'note'],
|
|
335
|
+
split: ['action', 'parts', 'note'],
|
|
336
|
+
}[action];
|
|
337
|
+
const required = {
|
|
338
|
+
pending: ['action'],
|
|
339
|
+
approve: ['action'],
|
|
340
|
+
revise: ['action', 'fields'],
|
|
341
|
+
reject: ['action'],
|
|
342
|
+
merge: ['action', 'into'],
|
|
343
|
+
split: ['action', 'parts'],
|
|
344
|
+
}[action];
|
|
345
|
+
assertKeys(decision, allowed, required, path);
|
|
346
|
+
const normalized = { action };
|
|
347
|
+
if (decision.note !== undefined) normalized.note = text(decision.note, `${path}.note`, true);
|
|
348
|
+
if (decision.fields !== undefined) {
|
|
349
|
+
assertMap(decision.fields, `${path}.fields`);
|
|
350
|
+
assertKeys(decision.fields, ACCEPTED_USE_CASE_FIELDS, [], `${path}.fields`);
|
|
351
|
+
normalized.fields = validateUseCaseFields(decision.fields, `${path}.fields`);
|
|
352
|
+
}
|
|
353
|
+
if (action === 'merge') {
|
|
354
|
+
normalized.into = useCaseId(decision.into, `${path}.into`);
|
|
355
|
+
if (normalized.into === id) throw new ReviewError(`${path}.into cannot merge a proposal into itself`);
|
|
356
|
+
}
|
|
357
|
+
if (action === 'split') {
|
|
358
|
+
normalized.parts = list(decision.parts, `${path}.parts`).map((part, index) =>
|
|
359
|
+
useCaseId(part, `${path}.parts[${index}]`),
|
|
360
|
+
);
|
|
361
|
+
if (new Set(normalized.parts).size !== normalized.parts.length) {
|
|
362
|
+
throw new ReviewError(`${path}.parts must be different use cases`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
proposals[id] = normalized;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
assertMap(value.mappings, 'review.mappings');
|
|
369
|
+
const subjects = new Set(subjectKeys);
|
|
370
|
+
const mappings = {};
|
|
371
|
+
for (const key of Object.keys(value.mappings).sort()) {
|
|
372
|
+
const path = `review.mappings.${key}`;
|
|
373
|
+
if (!subjects.has(key)) throw new ReviewError(`${path} names an unknown surface or workflow`);
|
|
374
|
+
const mapping = value.mappings[key];
|
|
375
|
+
assertMap(mapping, path);
|
|
376
|
+
assertKeys(mapping, ['disposition', 'useCaseIds', 'rationale'], ['disposition', 'useCaseIds', 'rationale'], path);
|
|
377
|
+
const useCaseIds = list(mapping.useCaseIds, `${path}.useCaseIds`).map((id, index) =>
|
|
378
|
+
useCaseId(id, `${path}.useCaseIds[${index}]`),
|
|
379
|
+
);
|
|
380
|
+
if (new Set(useCaseIds).size !== useCaseIds.length) {
|
|
381
|
+
throw new ReviewError(`${path}.useCaseIds must not repeat a use case`);
|
|
382
|
+
}
|
|
383
|
+
mappings[key] = {
|
|
384
|
+
disposition: oneOf(mapping.disposition, MAPPING_DISPOSITIONS, `${path}.disposition`),
|
|
385
|
+
useCaseIds,
|
|
386
|
+
rationale: text(mapping.rationale, `${path}.rationale`, true),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
kind: USE_CASE_REVIEW_KIND,
|
|
391
|
+
version: USE_CASE_REVIEW_VERSION,
|
|
392
|
+
approval: { status: 'unapproved', activatesCatalog: false },
|
|
393
|
+
candidate,
|
|
394
|
+
revision: value.revision,
|
|
395
|
+
proposals,
|
|
396
|
+
added,
|
|
397
|
+
mappings,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export function validateReviewDecisionCompleteness(candidate, review) {
|
|
402
|
+
const proposals = new Map(candidate.proposals.map((proposal) => [proposal.id, proposal]));
|
|
403
|
+
for (const [id, decision] of Object.entries(review.proposals)) {
|
|
404
|
+
const proposal = proposals.get(id);
|
|
405
|
+
if (!proposal) continue;
|
|
406
|
+
if (decision.action === 'approve') {
|
|
407
|
+
const completeness = useCaseCompleteness(proposal);
|
|
408
|
+
if (proposal.definitionStatus === 'draft') {
|
|
409
|
+
throw new ReviewError(
|
|
410
|
+
`${id} is an incomplete draft and cannot be approved as proposed; complete ${completeness.missingLabels.join(', ')} and accept the completed use case instead`,
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (decision.action === 'revise') {
|
|
415
|
+
const changedFields = actualChangedFields(proposal, decision.fields ?? {});
|
|
416
|
+
if (changedFields.length === 0) {
|
|
417
|
+
throw new ReviewError(
|
|
418
|
+
proposal.definitionStatus === 'draft'
|
|
419
|
+
? `${id} cannot accept the completed use case until at least one field is changed`
|
|
420
|
+
: `${id} cannot use revised approval data until at least one field differs from the assessment proposal`,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
const completeness = useCaseCompleteness({ ...proposal, ...decision.fields });
|
|
424
|
+
if (!completeness.complete) {
|
|
425
|
+
throw new ReviewError(
|
|
426
|
+
`${id} cannot ${
|
|
427
|
+
proposal.definitionStatus === 'draft'
|
|
428
|
+
? 'accept the completed use case'
|
|
429
|
+
: 'approve this use case'
|
|
430
|
+
} until ${completeness.missingLabels.join(', ')} ${
|
|
431
|
+
completeness.missingLabels.length === 1 ? 'is' : 'are'
|
|
432
|
+
} provided`,
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return review;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export function serializeReview(review) {
|
|
441
|
+
return `${JSON.stringify(canonicalize(review), null, 2)}\n`;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export function reviewSubjects(candidate, discoveredSurfaces = []) {
|
|
445
|
+
const subjects = [];
|
|
446
|
+
for (const surface of candidate.surfaces) subjects.push({ type: 'surface', origin: 'candidate', ...surface });
|
|
447
|
+
for (const workflow of candidate.workflows) subjects.push({ type: 'workflow', origin: 'candidate', ...workflow });
|
|
448
|
+
const known = new Set(candidate.surfaces.map(({ id }) => id));
|
|
449
|
+
for (const surface of [...discoveredSurfaces].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
450
|
+
if (known.has(surface.id)) continue;
|
|
451
|
+
known.add(surface.id);
|
|
452
|
+
subjects.push({
|
|
453
|
+
type: 'surface',
|
|
454
|
+
origin: 'discovered',
|
|
455
|
+
id: surface.id,
|
|
456
|
+
label: surface.label || surface.id,
|
|
457
|
+
route: surface.route,
|
|
458
|
+
kind: surface.hidden ? 'hidden' : 'destination',
|
|
459
|
+
sources: [surface.file],
|
|
460
|
+
classification: {
|
|
461
|
+
disposition: 'unresolved',
|
|
462
|
+
useCaseIds: [],
|
|
463
|
+
rationale: 'Found in configured navigation source but missing from the candidate.',
|
|
464
|
+
},
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
return subjects.map((subject) => ({ ...subject, key: subjectKey(subject.type, subject.id) }));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// computeReview is the single source of review semantics for the CLI, the
|
|
471
|
+
// local app, and adoption. It never mutates its inputs.
|
|
472
|
+
export function computeReview({
|
|
473
|
+
candidate,
|
|
474
|
+
review,
|
|
475
|
+
activeCatalog = { path: candidate.source.catalog, origin: 'candidate', text: null },
|
|
476
|
+
discoveredSurfaces = [],
|
|
477
|
+
identity = { status: 'unverified', reasons: [] },
|
|
478
|
+
}) {
|
|
479
|
+
const issues = [];
|
|
480
|
+
const issue = (severity, scope, message) => issues.push({ severity, scope, message });
|
|
481
|
+
const subjects = reviewSubjects(candidate, discoveredSurfaces);
|
|
482
|
+
const decisions = review.proposals;
|
|
483
|
+
|
|
484
|
+
let existingCatalog = null;
|
|
485
|
+
if (activeCatalog.text !== null) {
|
|
486
|
+
try {
|
|
487
|
+
const parsed = parseYamlSubset(activeCatalog.text);
|
|
488
|
+
if (!isMap(parsed) || parsed.version !== 1 || !Array.isArray(parsed.use_cases)) {
|
|
489
|
+
throw new ConfigError('catalog must be a version 1 mapping with use_cases');
|
|
490
|
+
}
|
|
491
|
+
if (!['partial', 'complete'].includes(parsed.inventory)) {
|
|
492
|
+
throw new ConfigError('catalog inventory must be partial or complete');
|
|
493
|
+
}
|
|
494
|
+
existingCatalog = parsed;
|
|
495
|
+
} catch (error) {
|
|
496
|
+
issue('error', 'catalog', `The active catalog ${activeCatalog.path} could not be read: ${error.message}`);
|
|
497
|
+
}
|
|
498
|
+
if (/^\s*#/m.test(activeCatalog.text)) {
|
|
499
|
+
issue(
|
|
500
|
+
'warning',
|
|
501
|
+
'catalog',
|
|
502
|
+
`Comments in ${activeCatalog.path} are not preserved by the generated catalog; the diff shows their removal.`,
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const existing = (existingCatalog?.use_cases ?? []).filter((entry) => isMap(entry) && typeof entry.id === 'string');
|
|
507
|
+
const existingIds = new Set(existing.map(({ id }) => id));
|
|
508
|
+
const candidateIds = new Set(candidate.proposals.map(({ id }) => id));
|
|
509
|
+
const addedById = new Map(review.added.map((entry) => [entry.id, entry]));
|
|
510
|
+
|
|
511
|
+
for (const entry of review.added) {
|
|
512
|
+
if (existingIds.has(entry.id)) issue('error', `use-case:${entry.id}`, `${entry.id} duplicates an active catalog use case.`);
|
|
513
|
+
}
|
|
514
|
+
for (const proposal of candidate.proposals) {
|
|
515
|
+
if (existingIds.has(proposal.id)) {
|
|
516
|
+
issue('error', `use-case:${proposal.id}`, `Proposal ${proposal.id} duplicates an active catalog use case; merge or rename it.`);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const proposals = candidate.proposals.map((proposal) => {
|
|
521
|
+
const decision = decisions[proposal.id] ?? { action: 'pending' };
|
|
522
|
+
const effective = {
|
|
523
|
+
...omit(proposal, ['capability', 'definitionStatus']),
|
|
524
|
+
...(decision.fields ?? {}),
|
|
525
|
+
};
|
|
526
|
+
const proposedCompleteness = useCaseCompleteness(proposal);
|
|
527
|
+
const draftCompleteness = useCaseCompleteness(effective);
|
|
528
|
+
const changedFields = actualChangedFields(proposal, decision.fields ?? {});
|
|
529
|
+
let action = decision.action;
|
|
530
|
+
let invalidDecision = null;
|
|
531
|
+
if (action === 'approve' && proposal.definitionStatus === 'draft') {
|
|
532
|
+
invalidDecision =
|
|
533
|
+
`This incomplete draft cannot be approved as proposed. Complete ${proposedCompleteness.missingLabels.join(', ')} ` +
|
|
534
|
+
'and accept the completed use case instead.';
|
|
535
|
+
action = 'pending';
|
|
536
|
+
} else if (action === 'revise' && (changedFields.length === 0 || !draftCompleteness.complete)) {
|
|
537
|
+
invalidDecision =
|
|
538
|
+
changedFields.length === 0
|
|
539
|
+
? proposal.definitionStatus === 'draft'
|
|
540
|
+
? 'A completed draft needs at least one changed field.'
|
|
541
|
+
: 'Revised approval data needs at least one changed field.'
|
|
542
|
+
: proposal.definitionStatus === 'draft'
|
|
543
|
+
? `The completed use case still needs ${draftCompleteness.missingLabels.join(', ')}.`
|
|
544
|
+
: `This use case still needs ${draftCompleteness.missingLabels.join(', ')}.`;
|
|
545
|
+
action = 'pending';
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
id: proposal.id,
|
|
549
|
+
origin: 'candidate',
|
|
550
|
+
definitionStatus: proposal.definitionStatus,
|
|
551
|
+
action,
|
|
552
|
+
recordedAction: decision.action,
|
|
553
|
+
note: decision.note ?? '',
|
|
554
|
+
into: decision.into ?? null,
|
|
555
|
+
parts: decision.parts ?? [],
|
|
556
|
+
capability: proposal.capability ?? 'unknown',
|
|
557
|
+
proposed: proposal,
|
|
558
|
+
effective,
|
|
559
|
+
proposedCompleteness,
|
|
560
|
+
draftCompleteness,
|
|
561
|
+
changedFields,
|
|
562
|
+
invalidDecision,
|
|
563
|
+
issues: [],
|
|
564
|
+
};
|
|
565
|
+
});
|
|
566
|
+
const added = review.added.map((entry) => ({
|
|
567
|
+
id: entry.id,
|
|
568
|
+
origin: entry.origin,
|
|
569
|
+
definitionStatus: null,
|
|
570
|
+
from: entry.from ?? null,
|
|
571
|
+
action: 'add',
|
|
572
|
+
note: '',
|
|
573
|
+
into: null,
|
|
574
|
+
parts: [],
|
|
575
|
+
capability: 'unknown',
|
|
576
|
+
proposed: null,
|
|
577
|
+
effective: omit(entry, ['origin', 'from']),
|
|
578
|
+
proposedCompleteness: null,
|
|
579
|
+
draftCompleteness: useCaseCompleteness(entry),
|
|
580
|
+
changedFields: [],
|
|
581
|
+
invalidDecision: null,
|
|
582
|
+
issues: [],
|
|
583
|
+
}));
|
|
584
|
+
const byId = new Map([...proposals, ...added].map((item) => [item.id, item]));
|
|
585
|
+
const accepted = (item) => item && ['approve', 'revise', 'add'].includes(item.action);
|
|
586
|
+
|
|
587
|
+
for (const item of proposals) {
|
|
588
|
+
const scope = `use-case:${item.id}`;
|
|
589
|
+
if (item.invalidDecision) {
|
|
590
|
+
item.issues.push({ severity: 'error', message: item.invalidDecision });
|
|
591
|
+
issue('error', scope, `${item.id}: ${item.invalidDecision}`);
|
|
592
|
+
}
|
|
593
|
+
if (item.action === 'merge') {
|
|
594
|
+
const target = byId.get(item.into);
|
|
595
|
+
if (!existingIds.has(item.into) && !accepted(target)) {
|
|
596
|
+
const message = target
|
|
597
|
+
? `${item.id} is merged into ${item.into}, which is not accepted; approve ${item.into} or choose another target.`
|
|
598
|
+
: `${item.id} is merged into unknown use case ${item.into}.`;
|
|
599
|
+
item.issues.push({ severity: 'error', message });
|
|
600
|
+
issue('error', scope, message);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
if (item.action === 'split') {
|
|
604
|
+
if (item.parts.length < 2) {
|
|
605
|
+
const message = `${item.id} is split but needs at least two parts.`;
|
|
606
|
+
item.issues.push({ severity: 'error', message });
|
|
607
|
+
issue('error', scope, message);
|
|
608
|
+
}
|
|
609
|
+
for (const part of item.parts) {
|
|
610
|
+
const entry = addedById.get(part);
|
|
611
|
+
if (!entry || entry.origin !== 'split' || entry.from !== item.id) {
|
|
612
|
+
const message = `${item.id} names split part ${part}, which is not a split part of this proposal.`;
|
|
613
|
+
item.issues.push({ severity: 'error', message });
|
|
614
|
+
issue('error', scope, message);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
for (const entry of added) {
|
|
620
|
+
if (entry.origin !== 'split') continue;
|
|
621
|
+
const parent = byId.get(entry.from);
|
|
622
|
+
if (parent?.action !== 'split' || !parent.parts.includes(entry.id)) {
|
|
623
|
+
const message = `${entry.id} is a split part of ${entry.from}, but ${entry.from} is not split into it.`;
|
|
624
|
+
entry.issues.push({ severity: 'error', message });
|
|
625
|
+
issue('error', `use-case:${entry.id}`, message);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// Resolution follows one merge hop; a merge target must itself be accepted.
|
|
630
|
+
const resolve = (id) => {
|
|
631
|
+
if (existingIds.has(id)) return { state: 'accepted', id };
|
|
632
|
+
const item = byId.get(id);
|
|
633
|
+
if (!item) return { state: 'broken', id, reason: `unknown use case ${id}` };
|
|
634
|
+
if (accepted(item)) return { state: 'accepted', id };
|
|
635
|
+
if (item.action === 'pending') return { state: 'pending', id };
|
|
636
|
+
if (item.action === 'merge') {
|
|
637
|
+
const target = byId.get(item.into);
|
|
638
|
+
if (existingIds.has(item.into) || accepted(target)) return { state: 'accepted', id: item.into, via: id };
|
|
639
|
+
return { state: 'broken', id, reason: `${id} is merged into ${item.into}, which is not accepted` };
|
|
640
|
+
}
|
|
641
|
+
if (item.action === 'split') return { state: 'broken', id, reason: `${id} was split; choose one of its parts` };
|
|
642
|
+
return { state: 'broken', id, reason: `${id} was rejected` };
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
const subjectResults = subjects.map((subject) => {
|
|
646
|
+
const override = review.mappings[subject.key];
|
|
647
|
+
const effective = override ?? fromClassification(subject.classification);
|
|
648
|
+
const result = {
|
|
649
|
+
key: subject.key,
|
|
650
|
+
type: subject.type,
|
|
651
|
+
id: subject.id,
|
|
652
|
+
label: subject.label ?? subject.title ?? subject.id,
|
|
653
|
+
route: subject.route ?? null,
|
|
654
|
+
entry: subject.entry ?? null,
|
|
655
|
+
kind: subject.kind ?? null,
|
|
656
|
+
capability: subject.capability ?? null,
|
|
657
|
+
sources: subject.sources,
|
|
658
|
+
origin: subject.origin,
|
|
659
|
+
proposed: subject.classification,
|
|
660
|
+
effective,
|
|
661
|
+
decided: Boolean(override),
|
|
662
|
+
resolvedUseCaseIds: [],
|
|
663
|
+
status: 'unresolved',
|
|
664
|
+
issues: [],
|
|
665
|
+
};
|
|
666
|
+
if (effective.disposition === 'excluded') {
|
|
667
|
+
if (effective.rationale.trim()) result.status = 'excluded';
|
|
668
|
+
else result.issues.push('An exclusion needs a rationale.');
|
|
669
|
+
} else if (effective.disposition === 'use-case') {
|
|
670
|
+
if (effective.useCaseIds.length === 0) {
|
|
671
|
+
result.issues.push('Choose at least one use case, exclude it with a rationale, or leave it unresolved.');
|
|
672
|
+
} else {
|
|
673
|
+
const resolutions = effective.useCaseIds.map(resolve);
|
|
674
|
+
const broken = resolutions.filter(({ state }) => state === 'broken');
|
|
675
|
+
for (const item of broken) result.issues.push(`Maps to ${item.reason}.`);
|
|
676
|
+
result.resolvedUseCaseIds = [...new Set(resolutions.filter(({ state }) => state === 'accepted').map(({ id }) => id))];
|
|
677
|
+
if (broken.length) result.status = 'unresolved';
|
|
678
|
+
else if (resolutions.some(({ state }) => state === 'pending')) result.status = 'proposed';
|
|
679
|
+
else result.status = 'mapped';
|
|
680
|
+
}
|
|
681
|
+
} else if (subject.origin === 'discovered') {
|
|
682
|
+
result.issues.push('Found in navigation source but not assessed by the candidate.');
|
|
683
|
+
}
|
|
684
|
+
return result;
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
const surfaceRoutes = new Map();
|
|
688
|
+
for (const subject of subjects) {
|
|
689
|
+
if (subject.type === 'surface' && typeof subject.route === 'string' && subject.route.startsWith('/')) {
|
|
690
|
+
surfaceRoutes.set(subject.id, subject.route);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
// Keep every assessed surface as a known legacy navigation id during
|
|
694
|
+
// validation. Its kind controls newly derived bindings below.
|
|
695
|
+
const validationSurfaces = [...surfaceRoutes].map(([id, route]) => ({ id, route }));
|
|
696
|
+
|
|
697
|
+
// Mapped navigation surfaces become navigation bindings. Hidden route
|
|
698
|
+
// surfaces remain route-only so they cannot impersonate navigation coverage.
|
|
699
|
+
const extraStarts = new Map();
|
|
700
|
+
for (const subject of subjectResults) {
|
|
701
|
+
if (subject.type !== 'surface' || subject.status !== 'mapped' || !surfaceRoutes.has(subject.id)) continue;
|
|
702
|
+
for (const id of subject.resolvedUseCaseIds) {
|
|
703
|
+
const starts = extraStarts.get(id) ?? [];
|
|
704
|
+
starts.push(
|
|
705
|
+
subject.kind === 'hidden'
|
|
706
|
+
? { entry: 'route', route: surfaceRoutes.get(subject.id) }
|
|
707
|
+
: { nav_id: subject.id, route: surfaceRoutes.get(subject.id) },
|
|
708
|
+
);
|
|
709
|
+
extraStarts.set(id, starts);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const merged = new Map();
|
|
713
|
+
for (const item of proposals) {
|
|
714
|
+
if (item.action !== 'merge') continue;
|
|
715
|
+
const resolution = resolve(item.id);
|
|
716
|
+
if (resolution.state !== 'accepted') continue;
|
|
717
|
+
const sources = merged.get(resolution.id) ?? [];
|
|
718
|
+
sources.push(item.effective);
|
|
719
|
+
merged.set(resolution.id, sources);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const entries = [];
|
|
723
|
+
const omitted = [];
|
|
724
|
+
const pushEntry = (id, base, existingEntry) => {
|
|
725
|
+
const entry = existingEntry ? structuredClone(existingEntry) : catalogFields(id, base);
|
|
726
|
+
for (const source of merged.get(id) ?? []) {
|
|
727
|
+
entry.starts = unionStarts(entry.starts, source.starts);
|
|
728
|
+
entry.requirements = unionText(entry.requirements, source.requirements);
|
|
729
|
+
entry.gaps = unionText(entry.gaps, source.gaps);
|
|
730
|
+
}
|
|
731
|
+
entry.starts = unionStarts(entry.starts, extraStarts.get(id));
|
|
732
|
+
for (const field of ['starts', 'requirements', 'gaps']) {
|
|
733
|
+
if (Array.isArray(entry[field]) && entry[field].length === 0) delete entry[field];
|
|
734
|
+
}
|
|
735
|
+
const missing = existingEntry ? [] : REQUIRED_FOR_CATALOG.filter((field) => isBlank(entry[field]));
|
|
736
|
+
if (missing.length) {
|
|
737
|
+
omitted.push({ id, reasons: [`missing ${missing.join(', ')}`] });
|
|
738
|
+
issue('error', `use-case:${id}`, `${id} cannot enter the catalog until ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} filled in.`);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
try {
|
|
742
|
+
validateCatalog({ version: 1, inventory: 'partial', use_cases: [entry] }, validationSurfaces);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
issue('error', `use-case:${id}`, `${id}: ${error.message}.`);
|
|
745
|
+
if (!existingEntry) {
|
|
746
|
+
omitted.push({ id, reasons: [error.message] });
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
entries.push(orderEntry(entry));
|
|
751
|
+
};
|
|
752
|
+
for (const entry of existing) pushEntry(entry.id, null, entry);
|
|
753
|
+
for (const item of [...proposals, ...added]) {
|
|
754
|
+
if (accepted(item) && !existingIds.has(item.id)) pushEntry(item.id, item.effective, null);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
for (const item of [...proposals, ...added]) {
|
|
758
|
+
item.catalogEntry = entries.find((entry) => entry.id === item.id) ?? null;
|
|
759
|
+
item.omitted = omitted.find((entry) => entry.id === item.id)?.reasons ?? [];
|
|
760
|
+
item.subjects = subjectResults
|
|
761
|
+
.filter((subject) => subject.effective.useCaseIds.includes(item.id))
|
|
762
|
+
.map(({ key }) => key);
|
|
763
|
+
if (!item.effective.outcome && candidate.outcomes.length) {
|
|
764
|
+
item.issues.push({ severity: 'warning', message: 'No user outcome is assigned.' });
|
|
765
|
+
}
|
|
766
|
+
const starts = Array.isArray(item.catalogEntry?.starts) ? item.catalogEntry.starts : [];
|
|
767
|
+
item.implementationCoverage = {
|
|
768
|
+
status: starts.length ? 'bound' : 'unknown',
|
|
769
|
+
entryPoints: starts.length,
|
|
770
|
+
};
|
|
771
|
+
if (item.catalogEntry && starts.length === 0) {
|
|
772
|
+
const message = 'No entry points are bound; implementation coverage is unknown.';
|
|
773
|
+
item.issues.push({ severity: 'warning', message });
|
|
774
|
+
issue('warning', `use-case:${item.id}`, `${item.id}: ${message}`);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
for (const subject of subjectResults) {
|
|
779
|
+
for (const message of subject.issues) issue(subject.status === 'unresolved' ? 'error' : 'warning', subject.key, message);
|
|
780
|
+
}
|
|
781
|
+
if (identity.status === 'stale') {
|
|
782
|
+
for (const reason of identity.reasons) issue('error', 'candidate', `Candidate is stale: ${reason}`);
|
|
783
|
+
}
|
|
784
|
+
if (activeCatalog.origin === 'candidate') {
|
|
785
|
+
issue(
|
|
786
|
+
'warning',
|
|
787
|
+
'catalog',
|
|
788
|
+
`No active ux-guard policy is configured. The candidate suggests ${activeCatalog.path}; adoption requires an explicit --catalog choice.`,
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
if (activeCatalog.mismatch) {
|
|
792
|
+
issue('warning', 'catalog', activeCatalog.mismatch);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const inventory = existingCatalog?.inventory ?? 'partial';
|
|
796
|
+
let catalogText = null;
|
|
797
|
+
if (entries.length === 0) {
|
|
798
|
+
issue('error', 'catalog', 'The generated catalog has no use cases yet; approve or add at least one.');
|
|
799
|
+
} else {
|
|
800
|
+
catalogText = emitCatalog({ version: 1, inventory, use_cases: entries });
|
|
801
|
+
}
|
|
802
|
+
const activeText = activeCatalog.text ?? '';
|
|
803
|
+
const diff = catalogText === null ? '' : unifiedDiff(activeText, catalogText, activeCatalog.path, activeCatalog.text === null);
|
|
804
|
+
|
|
805
|
+
const counts = (values, statuses) =>
|
|
806
|
+
Object.fromEntries(statuses.map((status) => [status, values.filter((value) => value === status).length]));
|
|
807
|
+
const subjectStatuses = ['mapped', 'proposed', 'excluded', 'unresolved'];
|
|
808
|
+
const pendingProposals = proposals.filter(({ action }) => action === 'pending');
|
|
809
|
+
const unresolved = [
|
|
810
|
+
...pendingProposals.map(({ id, effective, definitionStatus }) => ({
|
|
811
|
+
scope: `use-case:${id}`,
|
|
812
|
+
message:
|
|
813
|
+
definitionStatus === 'draft'
|
|
814
|
+
? `Complete, reject, merge, or split the incomplete draft “${effective.title}”.`
|
|
815
|
+
: `Decide whether to approve, reject, merge, or split “${effective.title}”.`,
|
|
816
|
+
})),
|
|
817
|
+
...subjectResults
|
|
818
|
+
.filter(({ status }) => status === 'unresolved')
|
|
819
|
+
.map(({ key, label, issues: subjectIssues }) => ({
|
|
820
|
+
scope: key,
|
|
821
|
+
message: subjectIssues[0] ? `${label}: ${subjectIssues[0]}` : `${label}: map it to a use case or exclude it with a rationale.`,
|
|
822
|
+
})),
|
|
823
|
+
];
|
|
824
|
+
const blocking = issues.filter(({ severity }) => severity === 'error');
|
|
825
|
+
return {
|
|
826
|
+
kind: 'ux-guard-use-case-review-state',
|
|
827
|
+
version: USE_CASE_REVIEW_VERSION,
|
|
828
|
+
approval: {
|
|
829
|
+
status: 'unapproved',
|
|
830
|
+
activatesCatalog: false,
|
|
831
|
+
notice: 'Saving records review decisions only. It does not approve, adopt, check in, or enforce anything.',
|
|
832
|
+
},
|
|
833
|
+
identity,
|
|
834
|
+
summary: {
|
|
835
|
+
discovered: subjectResults.length,
|
|
836
|
+
...counts(subjectResults.map(({ status }) => status), subjectStatuses),
|
|
837
|
+
surfaces: {
|
|
838
|
+
total: subjectResults.filter(({ type }) => type === 'surface').length,
|
|
839
|
+
...counts(subjectResults.filter(({ type }) => type === 'surface').map(({ status }) => status), subjectStatuses),
|
|
840
|
+
},
|
|
841
|
+
workflows: {
|
|
842
|
+
total: subjectResults.filter(({ type }) => type === 'workflow').length,
|
|
843
|
+
...counts(subjectResults.filter(({ type }) => type === 'workflow').map(({ status }) => status), subjectStatuses),
|
|
844
|
+
},
|
|
845
|
+
proposals: {
|
|
846
|
+
total: proposals.length,
|
|
847
|
+
decided: proposals.length - pendingProposals.length,
|
|
848
|
+
...counts(proposals.map(({ action }) => action), ACTIONS),
|
|
849
|
+
added: added.filter(({ origin }) => origin === 'added').length,
|
|
850
|
+
splitParts: added.filter(({ origin }) => origin === 'split').length,
|
|
851
|
+
},
|
|
852
|
+
definitions: {
|
|
853
|
+
completeProposals: proposals.filter(({ definitionStatus }) => definitionStatus === 'proposal').length,
|
|
854
|
+
incompleteDrafts: proposals.filter(({ definitionStatus }) => definitionStatus === 'draft').length,
|
|
855
|
+
completedDrafts: proposals.filter(
|
|
856
|
+
({ definitionStatus, draftCompleteness }) =>
|
|
857
|
+
definitionStatus === 'draft' && draftCompleteness.complete,
|
|
858
|
+
).length,
|
|
859
|
+
acceptedCompletedDrafts: proposals.filter(
|
|
860
|
+
({ definitionStatus, action }) => definitionStatus === 'draft' && action === 'revise',
|
|
861
|
+
).length,
|
|
862
|
+
approvedRevisedProposals: proposals.filter(
|
|
863
|
+
({ definitionStatus, action }) => definitionStatus === 'proposal' && action === 'revise',
|
|
864
|
+
).length,
|
|
865
|
+
decisionsNeeded: pendingProposals.length,
|
|
866
|
+
},
|
|
867
|
+
unresolvedDecisions: unresolved.length,
|
|
868
|
+
blockingIssues: blocking.length,
|
|
869
|
+
readyForOwnerApproval: unresolved.length === 0 && blocking.length === 0,
|
|
870
|
+
},
|
|
871
|
+
outcomes: groupOutcomes(candidate.outcomes, [...proposals, ...added]),
|
|
872
|
+
useCases: [...proposals, ...added],
|
|
873
|
+
existingUseCases: existing.map((entry) => {
|
|
874
|
+
const subjectMatches = subjectResults.filter((subject) => subject.resolvedUseCaseIds.includes(entry.id));
|
|
875
|
+
return {
|
|
876
|
+
id: entry.id,
|
|
877
|
+
title: typeof entry.title === 'string' ? entry.title : entry.id,
|
|
878
|
+
goal: typeof entry.goal === 'string' ? entry.goal : '',
|
|
879
|
+
success: typeof entry.success === 'string' ? entry.success : '',
|
|
880
|
+
tier: entry.tier ?? null,
|
|
881
|
+
effect: entry.effect ?? null,
|
|
882
|
+
starts: Array.isArray(entry.starts) ? structuredClone(entry.starts) : [],
|
|
883
|
+
entryPoints: Array.isArray(entry.starts) ? entry.starts.length : 0,
|
|
884
|
+
surfaces: subjectMatches.filter(({ type }) => type === 'surface').length,
|
|
885
|
+
workflows: subjectMatches.filter(({ type }) => type === 'workflow').length,
|
|
886
|
+
};
|
|
887
|
+
}),
|
|
888
|
+
subjects: subjectResults,
|
|
889
|
+
questions: candidate.questions,
|
|
890
|
+
unresolved,
|
|
891
|
+
issues,
|
|
892
|
+
catalog: {
|
|
893
|
+
path: activeCatalog.path,
|
|
894
|
+
origin: activeCatalog.origin,
|
|
895
|
+
exists: activeCatalog.text !== null,
|
|
896
|
+
activeSha256: activeCatalog.text === null ? null : sha256(activeCatalog.text),
|
|
897
|
+
inventory,
|
|
898
|
+
text: catalogText,
|
|
899
|
+
sha256: catalogText === null ? null : sha256(catalogText),
|
|
900
|
+
entries: entries.length,
|
|
901
|
+
unbound: entries.filter((entry) => !Array.isArray(entry.starts) || entry.starts.length === 0).map(({ id }) => id),
|
|
902
|
+
omitted,
|
|
903
|
+
diff,
|
|
904
|
+
changed: catalogText !== null && catalogText !== activeText,
|
|
905
|
+
},
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
export function previewText(state) {
|
|
910
|
+
return state.catalog.text === null ? null : `${PREVIEW_MARKER}\n${state.catalog.text}`;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function fromClassification(classification) {
|
|
914
|
+
if (classification.disposition === 'excluded') {
|
|
915
|
+
return { disposition: 'excluded', useCaseIds: [], rationale: classification.rationale };
|
|
916
|
+
}
|
|
917
|
+
if (classification.disposition === 'unresolved') {
|
|
918
|
+
return { disposition: 'unresolved', useCaseIds: [...classification.useCaseIds], rationale: classification.rationale };
|
|
919
|
+
}
|
|
920
|
+
return { disposition: 'use-case', useCaseIds: [...classification.useCaseIds], rationale: classification.rationale };
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function groupOutcomes(outcomes, items) {
|
|
924
|
+
const groups = outcomes.map((outcome) => ({ ...outcome, useCaseIds: [] }));
|
|
925
|
+
const byId = new Map(groups.map((group) => [group.id, group]));
|
|
926
|
+
const other = { id: '', title: 'No outcome assigned', summary: '', useCaseIds: [] };
|
|
927
|
+
for (const item of items) {
|
|
928
|
+
(byId.get(item.effective.outcome) ?? other).useCaseIds.push(item.id);
|
|
929
|
+
}
|
|
930
|
+
return other.useCaseIds.length ? [...groups, other] : groups;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function catalogFields(id, base) {
|
|
934
|
+
const entry = { id };
|
|
935
|
+
for (const field of CATALOG_ORDER.slice(1)) {
|
|
936
|
+
if (base[field] !== undefined) entry[field] = structuredClone(base[field]);
|
|
937
|
+
}
|
|
938
|
+
return entry;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
function orderEntry(entry) {
|
|
942
|
+
const ordered = {};
|
|
943
|
+
for (const field of CATALOG_ORDER) if (entry[field] !== undefined) ordered[field] = entry[field];
|
|
944
|
+
for (const field of Object.keys(entry)) if (!CATALOG_ORDER.includes(field)) ordered[field] = entry[field];
|
|
945
|
+
return ordered;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function unionStarts(current = [], extra = []) {
|
|
949
|
+
const starts = Array.isArray(current) ? [...current] : [];
|
|
950
|
+
const seen = new Set(starts.map((start) => JSON.stringify(canonicalize(start))));
|
|
951
|
+
for (const start of extra ?? []) {
|
|
952
|
+
const key = JSON.stringify(canonicalize(start));
|
|
953
|
+
if (seen.has(key)) continue;
|
|
954
|
+
seen.add(key);
|
|
955
|
+
starts.push(structuredClone(start));
|
|
956
|
+
}
|
|
957
|
+
return starts;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function unionText(current = [], extra = []) {
|
|
961
|
+
const values = Array.isArray(current) ? [...current] : [];
|
|
962
|
+
for (const value of extra ?? []) if (!values.includes(value)) values.push(value);
|
|
963
|
+
return values;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function actualChangedFields(proposal, fields) {
|
|
967
|
+
return Object.keys(fields).filter(
|
|
968
|
+
(field) => JSON.stringify(canonicalize(proposal[field] ?? null)) !== JSON.stringify(canonicalize(fields[field] ?? null)),
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function isBlank(value) {
|
|
973
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
974
|
+
return typeof value !== 'string' || !value.trim();
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// emitCatalog writes the strict YAML subset and proves the result parses back
|
|
978
|
+
// to the same value.
|
|
979
|
+
export function emitCatalog(catalog) {
|
|
980
|
+
const lines = emitMap(catalog, 0);
|
|
981
|
+
const text = `${lines.join('\n')}\n`;
|
|
982
|
+
let parsed;
|
|
983
|
+
try {
|
|
984
|
+
parsed = parseYamlSubset(text);
|
|
985
|
+
} catch (error) {
|
|
986
|
+
throw new ReviewError(`generated catalog is not valid YAML: ${error.message}`);
|
|
987
|
+
}
|
|
988
|
+
if (JSON.stringify(canonicalize(parsed)) !== JSON.stringify(canonicalize(catalog))) {
|
|
989
|
+
throw new ReviewError('generated catalog does not round-trip through the catalog parser');
|
|
990
|
+
}
|
|
991
|
+
return text;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
function emitMap(map, indent) {
|
|
995
|
+
const pad = ' '.repeat(indent);
|
|
996
|
+
const lines = [];
|
|
997
|
+
for (const [key, value] of Object.entries(map)) {
|
|
998
|
+
if (!/^[^\s:"'#]+$/.test(key)) throw new ReviewError(`catalog key ${JSON.stringify(key)} cannot be written`);
|
|
999
|
+
if (isScalar(value)) lines.push(`${pad}${key}: ${scalar(value)}`);
|
|
1000
|
+
else if (Array.isArray(value) && value.length === 0) continue;
|
|
1001
|
+
else lines.push(`${pad}${key}:`, ...emitNode(value, indent + 2));
|
|
1002
|
+
}
|
|
1003
|
+
return lines;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
function emitNode(value, indent) {
|
|
1007
|
+
if (Array.isArray(value)) return emitList(value, indent);
|
|
1008
|
+
if (isMap(value)) return emitMap(value, indent);
|
|
1009
|
+
throw new ReviewError('catalog values must be text, numbers, booleans, lists, or mappings');
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
function emitList(items, indent) {
|
|
1013
|
+
const pad = ' '.repeat(indent);
|
|
1014
|
+
const lines = [];
|
|
1015
|
+
for (const item of items) {
|
|
1016
|
+
if (isScalar(item)) {
|
|
1017
|
+
lines.push(`${pad}- ${scalar(item)}`);
|
|
1018
|
+
} else if (isMap(item)) {
|
|
1019
|
+
const [first, ...rest] = Object.entries(item);
|
|
1020
|
+
if (!first) throw new ReviewError('catalog lists cannot contain empty mappings');
|
|
1021
|
+
const [key, value] = first;
|
|
1022
|
+
if (isScalar(value)) lines.push(`${pad}- ${key}: ${scalar(value)}`);
|
|
1023
|
+
else lines.push(`${pad}- ${key}:`, ...emitNode(value, indent + 4));
|
|
1024
|
+
lines.push(...emitMap(Object.fromEntries(rest), indent + 2));
|
|
1025
|
+
} else {
|
|
1026
|
+
throw new ReviewError('catalog lists cannot contain nested lists');
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return lines;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
function isScalar(value) {
|
|
1033
|
+
return typeof value === 'string' || typeof value === 'boolean' || (Number.isSafeInteger(value) && value >= 0);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function scalar(value) {
|
|
1037
|
+
if (typeof value !== 'string') return String(value);
|
|
1038
|
+
if (/[\r\n\t]/.test(value)) throw new ReviewError('catalog text cannot contain line breaks or tabs');
|
|
1039
|
+
const plain =
|
|
1040
|
+
/^[A-Za-z0-9_/.@][A-Za-z0-9 _/.@()&,+-]*$/.test(value) &&
|
|
1041
|
+
!value.endsWith(' ') &&
|
|
1042
|
+
!['true', 'false'].includes(value) &&
|
|
1043
|
+
!/^\d+$/.test(value);
|
|
1044
|
+
if (plain) return value;
|
|
1045
|
+
if (!value.includes('"')) return `"${value}"`;
|
|
1046
|
+
if (!value.includes("'")) return `'${value}'`;
|
|
1047
|
+
throw new ReviewError('catalog text cannot contain both single and double quotes');
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// unifiedDiff produces a deterministic line diff with three lines of context.
|
|
1051
|
+
export function unifiedDiff(before, after, path, created = false) {
|
|
1052
|
+
const a = splitLines(before);
|
|
1053
|
+
const b = splitLines(after);
|
|
1054
|
+
const ops = diffLines(a, b);
|
|
1055
|
+
let oldPosition = 0;
|
|
1056
|
+
let newPosition = 0;
|
|
1057
|
+
for (const op of ops) {
|
|
1058
|
+
op.old = oldPosition;
|
|
1059
|
+
op.new = newPosition;
|
|
1060
|
+
if (op.type !== 'add') oldPosition += 1;
|
|
1061
|
+
if (op.type !== 'remove') newPosition += 1;
|
|
1062
|
+
}
|
|
1063
|
+
const changes = ops.flatMap((op, index) => (op.type === 'same' ? [] : [index]));
|
|
1064
|
+
if (changes.length === 0) return '';
|
|
1065
|
+
const context = 3;
|
|
1066
|
+
const lines = [created ? '--- /dev/null' : `--- a/${path}`, `+++ b/${path}`];
|
|
1067
|
+
let cursor = 0;
|
|
1068
|
+
while (cursor < changes.length) {
|
|
1069
|
+
const start = Math.max(0, changes[cursor] - context);
|
|
1070
|
+
let end = Math.min(ops.length, changes[cursor] + context + 1);
|
|
1071
|
+
cursor += 1;
|
|
1072
|
+
while (cursor < changes.length && changes[cursor] - context <= end) {
|
|
1073
|
+
end = Math.min(ops.length, changes[cursor] + context + 1);
|
|
1074
|
+
cursor += 1;
|
|
1075
|
+
}
|
|
1076
|
+
const slice = ops.slice(start, end);
|
|
1077
|
+
const oldCount = slice.filter(({ type }) => type !== 'add').length;
|
|
1078
|
+
const newCount = slice.filter(({ type }) => type !== 'remove').length;
|
|
1079
|
+
const oldStart = oldCount ? slice[0].old + 1 : slice[0].old;
|
|
1080
|
+
const newStart = newCount ? slice[0].new + 1 : slice[0].new;
|
|
1081
|
+
lines.push(
|
|
1082
|
+
`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`,
|
|
1083
|
+
...slice.map(({ type, text }) => `${type === 'add' ? '+' : type === 'remove' ? '-' : ' '}${text}`),
|
|
1084
|
+
);
|
|
1085
|
+
}
|
|
1086
|
+
return `${lines.join('\n')}\n`;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function splitLines(text) {
|
|
1090
|
+
if (!text) return [];
|
|
1091
|
+
const lines = text.split(/\r?\n/);
|
|
1092
|
+
if (lines.at(-1) === '') lines.pop();
|
|
1093
|
+
return lines;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
function diffLines(a, b) {
|
|
1097
|
+
const n = a.length;
|
|
1098
|
+
const m = b.length;
|
|
1099
|
+
if (n === 0) return b.map((text) => ({ type: 'add', text }));
|
|
1100
|
+
if (m === 0) return a.map((text) => ({ type: 'remove', text }));
|
|
1101
|
+
const max = n + m;
|
|
1102
|
+
const offset = max;
|
|
1103
|
+
let v = new Int32Array(2 * max + 2);
|
|
1104
|
+
const trace = [];
|
|
1105
|
+
let found = n === 0 && m === 0;
|
|
1106
|
+
for (let d = 0; d <= max && !found; d += 1) {
|
|
1107
|
+
trace.push(v.slice());
|
|
1108
|
+
for (let k = -d; k <= d; k += 2) {
|
|
1109
|
+
let x;
|
|
1110
|
+
if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) x = v[offset + k + 1];
|
|
1111
|
+
else x = v[offset + k - 1] + 1;
|
|
1112
|
+
let y = x - k;
|
|
1113
|
+
while (x < n && y < m && a[x] === b[y]) {
|
|
1114
|
+
x += 1;
|
|
1115
|
+
y += 1;
|
|
1116
|
+
}
|
|
1117
|
+
v[offset + k] = x;
|
|
1118
|
+
if (x >= n && y >= m) {
|
|
1119
|
+
found = true;
|
|
1120
|
+
break;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
const ops = [];
|
|
1125
|
+
let x = n;
|
|
1126
|
+
let y = m;
|
|
1127
|
+
for (let d = trace.length - 1; d >= 0; d -= 1) {
|
|
1128
|
+
const previous = trace[d];
|
|
1129
|
+
const k = x - y;
|
|
1130
|
+
let prevK;
|
|
1131
|
+
if (k === -d || (k !== d && previous[offset + k - 1] < previous[offset + k + 1])) prevK = k + 1;
|
|
1132
|
+
else prevK = k - 1;
|
|
1133
|
+
const prevX = d === 0 ? 0 : previous[offset + prevK];
|
|
1134
|
+
const prevY = d === 0 ? 0 : prevX - prevK;
|
|
1135
|
+
while (x > prevX && y > prevY) {
|
|
1136
|
+
ops.push({ type: 'same', text: a[x - 1] });
|
|
1137
|
+
x -= 1;
|
|
1138
|
+
y -= 1;
|
|
1139
|
+
}
|
|
1140
|
+
if (d === 0) break;
|
|
1141
|
+
if (x === prevX) ops.push({ type: 'add', text: b[y - 1] });
|
|
1142
|
+
else ops.push({ type: 'remove', text: a[x - 1] });
|
|
1143
|
+
x = prevX;
|
|
1144
|
+
y = prevY;
|
|
1145
|
+
}
|
|
1146
|
+
return ops.reverse();
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
function validateSource(value, path, draft) {
|
|
1150
|
+
assertMap(value, path);
|
|
1151
|
+
if (draft) {
|
|
1152
|
+
for (const field of ['repository', 'commit', 'inputs']) {
|
|
1153
|
+
if (Object.hasOwn(value, field)) {
|
|
1154
|
+
throw new ReviewError(`${path}.${field} is computed by ux-guard review prepare; remove it from the draft`);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
assertKeys(value, ['catalog', 'navigation'], ['catalog', 'navigation'], path);
|
|
1158
|
+
} else {
|
|
1159
|
+
assertKeys(
|
|
1160
|
+
value,
|
|
1161
|
+
['repository', 'commit', 'catalog', 'navigation', 'inputs'],
|
|
1162
|
+
['repository', 'commit', 'catalog', 'navigation', 'inputs'],
|
|
1163
|
+
path,
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
const source = {
|
|
1167
|
+
catalog: repositoryPath(value.catalog, `${path}.catalog`),
|
|
1168
|
+
navigation: list(value.navigation, `${path}.navigation`).map((item, index) =>
|
|
1169
|
+
repositoryPath(item, `${path}.navigation[${index}]`),
|
|
1170
|
+
),
|
|
1171
|
+
};
|
|
1172
|
+
if (new Set(source.navigation).size !== source.navigation.length) {
|
|
1173
|
+
throw new ReviewError(`${path}.navigation must not repeat a file`);
|
|
1174
|
+
}
|
|
1175
|
+
if (draft) return source;
|
|
1176
|
+
assertMap(value.repository, `${path}.repository`);
|
|
1177
|
+
assertKeys(value.repository, ['rootCommits'], ['rootCommits'], `${path}.repository`);
|
|
1178
|
+
const rootCommits = list(value.repository.rootCommits, `${path}.repository.rootCommits`).map((item, index) =>
|
|
1179
|
+
commit(item, `${path}.repository.rootCommits[${index}]`),
|
|
1180
|
+
);
|
|
1181
|
+
if (value.commit !== null) commit(value.commit, `${path}.commit`);
|
|
1182
|
+
const inputs = list(value.inputs, `${path}.inputs`).map((item, index) => {
|
|
1183
|
+
const itemPath = `${path}.inputs[${index}]`;
|
|
1184
|
+
assertMap(item, itemPath);
|
|
1185
|
+
assertKeys(item, ['path', 'sha256'], ['path', 'sha256'], itemPath);
|
|
1186
|
+
return { path: repositoryPath(item.path, `${itemPath}.path`), sha256: hash(item.sha256, `${itemPath}.sha256`) };
|
|
1187
|
+
});
|
|
1188
|
+
const paths = inputs.map(({ path: inputPath }) => inputPath);
|
|
1189
|
+
if (paths.join('\n') !== [...new Set(paths)].sort().join('\n')) {
|
|
1190
|
+
throw new ReviewError(`${path}.inputs must be unique and sorted by path`);
|
|
1191
|
+
}
|
|
1192
|
+
return {
|
|
1193
|
+
repository: { rootCommits },
|
|
1194
|
+
commit: value.commit,
|
|
1195
|
+
...source,
|
|
1196
|
+
inputs,
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
function validateOutcome(value, path) {
|
|
1201
|
+
assertMap(value, path);
|
|
1202
|
+
assertKeys(value, ['id', 'title', 'summary'], ['id', 'title'], path);
|
|
1203
|
+
const outcome = { id: useCaseId(value.id, `${path}.id`), title: text(value.title, `${path}.title`) };
|
|
1204
|
+
if (value.summary !== undefined) outcome.summary = text(value.summary, `${path}.summary`, true);
|
|
1205
|
+
return outcome;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
function validateSubject(value, path, type) {
|
|
1209
|
+
assertMap(value, path);
|
|
1210
|
+
const fields =
|
|
1211
|
+
type === 'surface'
|
|
1212
|
+
? ['id', 'label', 'route', 'kind', 'sources', 'classification']
|
|
1213
|
+
: ['id', 'title', 'entry', 'capability', 'sources', 'classification'];
|
|
1214
|
+
const required = type === 'surface' ? ['id', 'label', 'classification'] : ['id', 'title', 'classification'];
|
|
1215
|
+
assertKeys(value, fields, required, path);
|
|
1216
|
+
const subject = { id: subjectId(value.id, `${path}.id`) };
|
|
1217
|
+
if (type === 'surface') {
|
|
1218
|
+
subject.label = text(value.label, `${path}.label`);
|
|
1219
|
+
if (value.route !== undefined) {
|
|
1220
|
+
subject.route = text(value.route, `${path}.route`);
|
|
1221
|
+
if (!subject.route.startsWith('/')) throw new ReviewError(`${path}.route must be absolute`);
|
|
1222
|
+
}
|
|
1223
|
+
subject.kind = value.kind === undefined ? 'destination' : oneOf(value.kind, SURFACE_KINDS, `${path}.kind`);
|
|
1224
|
+
} else {
|
|
1225
|
+
subject.title = text(value.title, `${path}.title`);
|
|
1226
|
+
if (value.entry !== undefined) subject.entry = text(value.entry, `${path}.entry`);
|
|
1227
|
+
subject.capability =
|
|
1228
|
+
value.capability === undefined ? 'unknown' : oneOf(value.capability, CAPABILITIES, `${path}.capability`);
|
|
1229
|
+
}
|
|
1230
|
+
subject.sources = list(value.sources, `${path}.sources`).map((item, index) =>
|
|
1231
|
+
repositoryPath(item, `${path}.sources[${index}]`),
|
|
1232
|
+
);
|
|
1233
|
+
const classification = value.classification;
|
|
1234
|
+
const classificationPath = `${path}.classification`;
|
|
1235
|
+
assertMap(classification, classificationPath);
|
|
1236
|
+
assertKeys(classification, ['disposition', 'useCaseIds', 'rationale'], ['disposition'], classificationPath);
|
|
1237
|
+
subject.classification = {
|
|
1238
|
+
disposition: oneOf(classification.disposition, DISPOSITIONS, `${classificationPath}.disposition`),
|
|
1239
|
+
useCaseIds: list(classification.useCaseIds, `${classificationPath}.useCaseIds`).map((id, index) =>
|
|
1240
|
+
useCaseId(id, `${classificationPath}.useCaseIds[${index}]`),
|
|
1241
|
+
),
|
|
1242
|
+
rationale: classification.rationale === undefined ? '' : text(classification.rationale, `${classificationPath}.rationale`, true),
|
|
1243
|
+
};
|
|
1244
|
+
return subject;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function validateUseCaseFields(value, path) {
|
|
1248
|
+
const fields = {};
|
|
1249
|
+
for (const field of TEXT_FIELDS) {
|
|
1250
|
+
if (value[field] !== undefined) fields[field] = text(value[field], `${path}.${field}`, field === 'rationale');
|
|
1251
|
+
}
|
|
1252
|
+
if (value.owner !== undefined) fields.owner = text(value.owner, `${path}.owner`);
|
|
1253
|
+
if (value.tier !== undefined) fields.tier = oneOf(value.tier, TIERS, `${path}.tier`);
|
|
1254
|
+
if (value.effect !== undefined) fields.effect = oneOf(value.effect, EFFECTS, `${path}.effect`);
|
|
1255
|
+
if (value.outcome !== undefined) fields.outcome = useCaseId(value.outcome, `${path}.outcome`);
|
|
1256
|
+
if (value.starts !== undefined) {
|
|
1257
|
+
fields.starts = list(value.starts, `${path}.starts`).map((start, index) =>
|
|
1258
|
+
validateStart(start, `${path}.starts[${index}]`),
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
for (const field of ['requirements', 'gaps']) {
|
|
1262
|
+
if (value[field] !== undefined) {
|
|
1263
|
+
fields[field] = list(value[field], `${path}.${field}`).map((item, index) =>
|
|
1264
|
+
text(item, `${path}.${field}[${index}]`),
|
|
1265
|
+
);
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
return fields;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
function validateStart(value, path) {
|
|
1272
|
+
assertMap(value, path);
|
|
1273
|
+
if (value.entry !== undefined) {
|
|
1274
|
+
if (value.entry === 'assistant') {
|
|
1275
|
+
assertKeys(value, ['entry', 'prompt'], ['entry', 'prompt'], path);
|
|
1276
|
+
return { entry: 'assistant', prompt: text(value.prompt, `${path}.prompt`) };
|
|
1277
|
+
}
|
|
1278
|
+
if (value.entry === 'route') {
|
|
1279
|
+
assertKeys(value, ['entry', 'route'], ['entry', 'route'], path);
|
|
1280
|
+
const route = text(value.route, `${path}.route`);
|
|
1281
|
+
if (!isCanonicalDirectRoute(route)) {
|
|
1282
|
+
throw new ReviewError(`${path}.route must be a canonical absolute route`);
|
|
1283
|
+
}
|
|
1284
|
+
return { entry: 'route', route };
|
|
1285
|
+
}
|
|
1286
|
+
throw new ReviewError(`${path}.entry must be assistant or route`);
|
|
1287
|
+
}
|
|
1288
|
+
assertKeys(value, ['nav_id', 'route'], ['nav_id', 'route'], path);
|
|
1289
|
+
const route = text(value.route, `${path}.route`);
|
|
1290
|
+
if (!route.startsWith('/')) throw new ReviewError(`${path}.route must be absolute`);
|
|
1291
|
+
return { nav_id: subjectId(value.nav_id, `${path}.nav_id`), route };
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
function assertUnapproved(value, path) {
|
|
1295
|
+
assertMap(value, path);
|
|
1296
|
+
assertKeys(value, ['status', 'activatesCatalog'], ['status', 'activatesCatalog'], path);
|
|
1297
|
+
if (value.status !== 'unapproved' || value.activatesCatalog !== false) {
|
|
1298
|
+
throw new ReviewError(
|
|
1299
|
+
`${path} must be unapproved with activatesCatalog false; approval happens only through ux-guard review adopt`,
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
function assertKeys(value, allowed, required, path) {
|
|
1305
|
+
for (const key of Object.keys(value)) {
|
|
1306
|
+
if (!allowed.includes(key)) throw new ReviewError(`${path}.${key} is not a recognized field`);
|
|
1307
|
+
}
|
|
1308
|
+
for (const key of required) {
|
|
1309
|
+
if (!Object.hasOwn(value, key)) throw new ReviewError(`${path}.${key} is required`);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
function assertMap(value, path) {
|
|
1314
|
+
if (!isMap(value)) throw new ReviewError(`${path} must be an object`);
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
function isMap(value) {
|
|
1318
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
function list(value, path) {
|
|
1322
|
+
if (value === undefined) return [];
|
|
1323
|
+
if (!Array.isArray(value)) throw new ReviewError(`${path} must be a list`);
|
|
1324
|
+
if (value.length > MAX_ITEMS) throw new ReviewError(`${path} has more than ${MAX_ITEMS} entries`);
|
|
1325
|
+
return value;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
function text(value, path, allowEmpty = false) {
|
|
1329
|
+
if (typeof value !== 'string') throw new ReviewError(`${path} must be text`);
|
|
1330
|
+
if (!allowEmpty && !value.trim()) throw new ReviewError(`${path} must not be empty`);
|
|
1331
|
+
if (value.length > MAX_TEXT) throw new ReviewError(`${path} is longer than ${MAX_TEXT} characters`);
|
|
1332
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)) {
|
|
1333
|
+
throw new ReviewError(`${path} contains control characters`);
|
|
1334
|
+
}
|
|
1335
|
+
return value;
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
function oneOf(value, values, path) {
|
|
1339
|
+
if (!values.includes(value)) throw new ReviewError(`${path} must be one of ${values.join(', ')}`);
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
function useCaseId(value, path) {
|
|
1344
|
+
if (typeof value !== 'string' || !USE_CASE_ID.test(value) || value.length > 120) {
|
|
1345
|
+
throw new ReviewError(`${path} must be a lowercase kebab-case use-case id`);
|
|
1346
|
+
}
|
|
1347
|
+
return value;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
function subjectId(value, path) {
|
|
1351
|
+
if (typeof value !== 'string' || !SUBJECT_ID.test(value)) {
|
|
1352
|
+
throw new ReviewError(`${path} must be a simple identifier`);
|
|
1353
|
+
}
|
|
1354
|
+
return value;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
function commit(value, path) {
|
|
1358
|
+
if (typeof value !== 'string' || !COMMIT.test(value)) throw new ReviewError(`${path} must be a Git object id`);
|
|
1359
|
+
return value;
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
function hash(value, path) {
|
|
1363
|
+
if (typeof value !== 'string' || !SHA256.test(value)) throw new ReviewError(`${path} must be a SHA-256 hex digest`);
|
|
1364
|
+
return value;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
function repositoryPath(value, path) {
|
|
1368
|
+
try {
|
|
1369
|
+
return assertRepositoryRelativePath(value, path);
|
|
1370
|
+
} catch (error) {
|
|
1371
|
+
throw new ReviewError(error.message);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
function uniqueIds(items, path) {
|
|
1376
|
+
const seen = new Set();
|
|
1377
|
+
for (const { id } of items) {
|
|
1378
|
+
if (seen.has(id)) throw new ReviewError(`${path} repeats id ${id}`);
|
|
1379
|
+
seen.add(id);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function omit(value, keys) {
|
|
1384
|
+
return Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
|
|
1385
|
+
}
|