rig-review 1.10.2 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';
3
+ import { extname, join, resolve } from 'node:path';
4
+ import { isDeepStrictEqual as equal } from 'node:util';
5
+
6
+ type RecordData = Record<string, unknown>;
7
+ export interface SetRef {path: string; sha256: string}
8
+ interface Option {id: string; kind: 'value' | 'other' | 'auto'; label: string; effect: string; recommended: boolean; reason?: string; fragment?: unknown}
9
+ interface Ask {id: string; prompt: string; options: Option[]}
10
+ interface Constraint {asks: string[]; allowed: string[][]}
11
+ export interface InterviewSet {
12
+ id: string; question: string; stage: string; drafted_by: string; drafted_at: string;
13
+ asks: Ask[]; assembly: {rule: 'single' | 'concat' | 'merge'}; constraints?: Constraint[];
14
+ }
15
+ interface Image {ref: SetRef; name: string; type: string}
16
+ export interface HistoricalInterview {question: string; verbatim: string; by?: string; at?: string}
17
+ export interface InterviewQuestion {ref: SetRef; set: InterviewSet; editable: boolean; images: Image[]; hasParts: boolean; partsUnavailable?: boolean; answer?: RecordData}
18
+ export const digest = (data: Buffer | string) => createHash('sha256').update(data).digest('hex');
19
+ export const object = (v: unknown): RecordData => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as RecordData : {};
20
+ const records = (v: unknown) => Array.isArray(v) ? v.map(object) : [];
21
+ const date = (v: unknown) => typeof v === 'string' ? Date.parse(v) : NaN;
22
+ export const invalid = (message: string): never => {throw new Error('INTERVIEW_CHOICE_INVALID: ' + message);};
23
+ const invalidOptions = (message: string): never => {throw new Error('INTERVIEW_OPTIONS_INVALID: ' + message);};
24
+ const stale = (message: string): never => {throw new Error('INTERVIEW_OPTIONS_STALE: ' + message);};
25
+ const text = (v: unknown): v is string => typeof v === 'string' && !!v.trim();
26
+ const id = (v: unknown): v is string => typeof v === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(v);
27
+ const stages = ['interview', 'plan-approved', 'parts', 'parts-review', 'rigging-interview', 'rigging', 'rig-review', 'post-interview', 'post', 'direction-review', 'accepted'];
28
+ const optionStages = ['interview', 'rigging-interview', 'post-interview'];
29
+
30
+ export function literalPath(path: unknown): path is string {
31
+ return typeof path === 'string' && path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..' && !/[\\:%\u0000-\u001f\u007f]/.test(segment));
32
+ }
33
+ export function checkedPath(root: string, path: string, directory = false): string {
34
+ if (!literalPath(path)) throw new Error('Invalid project-relative path');
35
+ let current = root;
36
+ const segments = path.split('/');
37
+ for (const [index, segment] of segments.entries()) {
38
+ current = join(current, segment);
39
+ const entry = lstatSync(current);
40
+ if (!(directory || index < segments.length - 1 ? entry.isDirectory() : entry.isFile())) throw new Error('Expected literal directory or regular file');
41
+ }
42
+ return current;
43
+ }
44
+ export function readRegular(path: string, limit: number): Buffer {
45
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
46
+ try {
47
+ const stat = fstatSync(fd);
48
+ if (!stat.isFile() || stat.size > limit) throw new Error('File type or size exceeds interview limits');
49
+ const bytes = Buffer.alloc(stat.size + 1);
50
+ let length = 0;
51
+ while (length < bytes.length) {
52
+ const count = readSync(fd, bytes, length, bytes.length - length, null);
53
+ if (!count) break;
54
+ length += count;
55
+ }
56
+ if (length !== stat.size) throw new Error('File changed during read');
57
+ return bytes.subarray(0, length);
58
+ } finally { closeSync(fd); }
59
+ }
60
+ function binding(v: unknown): SetRef {
61
+ const {path, sha256} = object(v);
62
+ if (!literalPath(path) || typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256)) return invalid('Malformed file binding');
63
+ return {path, sha256};
64
+ }
65
+ export function boundBytes(root: string, ref: SetRef): Buffer {
66
+ const bytes = readRegular(checkedPath(root, ref.path), 64 * 1024 * 1024);
67
+ if (digest(bytes) !== ref.sha256) throw new Error('Raw SHA-256 differs');
68
+ return bytes;
69
+ }
70
+ export function jsonObject(bytes: Buffer): RecordData {
71
+ const value = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes));
72
+ if (object(value) !== value) return invalid('Expected a JSON object');
73
+ return value;
74
+ }
75
+
76
+ function readSet(root: string, ref: SetRef): RecordData {
77
+ try {
78
+ if (['derived', 'outputs', 'scratch', 'node_modules', '.git'].includes(ref.path.split('/')[0]!)) throw new Error('Option files require retained storage');
79
+ return jsonObject(boundBytes(root, ref));
80
+ } catch (error) {
81
+ if (error instanceof Error && error.message === 'Raw SHA-256 differs') return stale(ref.path);
82
+ throw new Error('INTERVIEW_OPTIONS_FILE: ' + ref.path);
83
+ }
84
+ }
85
+
86
+ function validateSet(raw: RecordData, question: unknown, allowedStages: string[]): InterviewSet {
87
+ const asks = records(raw.asks);
88
+ const rule = object(raw.assembly).rule;
89
+ if (raw.schema !== 'rig-create/interview-options@1' || !id(raw.id) || raw.question !== question || !id(question) ||
90
+ !allowedStages.includes(String(raw.stage)) || !text(raw.drafted_by) || !Number.isFinite(date(raw.drafted_at)) ||
91
+ !asks.length || new Set(asks.map(ask => ask.id)).size !== asks.length ||
92
+ !['single', 'concat', 'merge'].includes(String(rule)) || (rule === 'single' && asks.length !== 1)) return invalidOptions('Invalid option set');
93
+ for (const ask of asks) {
94
+ const options = records(ask.options);
95
+ if (!id(ask.id) || !text(ask.prompt) || new Set(options.map(option => option.id)).size !== options.length ||
96
+ options.filter(option => option.kind === 'value').length < 2 ||
97
+ options.filter(option => option.kind === 'other').length !== 1 ||
98
+ options.filter(option => option.kind === 'auto').length !== 1 ||
99
+ options.filter(option => option.recommended === true).length !== 1) return invalidOptions('Invalid ask or recommendation');
100
+ for (const option of options) {
101
+ if (!id(option.id) || !text(option.label) || !text(option.effect) || typeof option.recommended !== 'boolean' ||
102
+ !['value', 'other', 'auto'].includes(String(option.kind)) ||
103
+ (option.recommended && (option.kind !== 'value' || !text(option.reason))) ||
104
+ (option.kind === 'value' ? !('fragment' in option) ||
105
+ (rule === 'concat' && !Array.isArray(option.fragment)) ||
106
+ (rule === 'merge' && object(option.fragment) !== option.fragment) : 'fragment' in option)) return invalidOptions('Invalid option');
107
+ }
108
+ }
109
+ if (raw.constraints !== undefined) {
110
+ if (!Array.isArray(raw.constraints)) return invalidOptions('Invalid constraints');
111
+ for (const constraint of records(raw.constraints)) {
112
+ const names = constraint.asks;
113
+ if (!Array.isArray(names) || !names.length || new Set(names).size !== names.length ||
114
+ names.some(name => !asks.some(ask => ask.id === name)) || !Array.isArray(constraint.allowed) ||
115
+ !constraint.allowed.length || constraint.allowed.some(tuple => !Array.isArray(tuple) || tuple.length !== names.length ||
116
+ tuple.some((value, index) => !records(asks.find(ask => ask.id === names[index])?.options)
117
+ .some(option => option.id === value && option.kind === 'value')))) return invalidOptions('Invalid constraint tuple');
118
+ }
119
+ }
120
+ return raw as unknown as InterviewSet;
121
+ }
122
+
123
+ function reopened(project: RecordData, stage: string, after: number, through: number): boolean {
124
+ return records(project.reopens).some(reopen => {
125
+ const index = stages.indexOf(String(reopen.stage));
126
+ const at = date(reopen.at);
127
+ return index >= 0 && index <= stages.indexOf(stage) && at > after && at <= through;
128
+ });
129
+ }
130
+ function approval(project: RecordData, stage: string, at: number) {
131
+ return records(project.signoffs).filter(s => s.stage === stage && (s.checkpoint === null || s.checkpoint === undefined) &&
132
+ text(s.by) && s.by.toLowerCase() !== 'agent' && date(s.at) <= at &&
133
+ !reopened(project, stage, date(s.at) - 1, at)).reverse().sort((a, b) => date(b.at) - date(a.at))[0];
134
+ }
135
+ function draftFor(project: RecordData, signoff: RecordData | undefined, at: number) {
136
+ return records(project.drafts).find(draft => draft.id === signoff?.draft_id && date(draft.at) <= at);
137
+ }
138
+ function contextAt(project: RecordData, stage: string, at: number): unknown {
139
+ if (stage === 'interview') return {kind: 'inputs', files: records(project.inputs)
140
+ .filter(file => file.at === undefined || date(file.at) <= at).map(({path, sha256}) => ({path, sha256}))};
141
+ if (stage === 'rigging-interview') {
142
+ const signoff = approval(project, 'parts-review', at);
143
+ const draft = draftFor(project, signoff, at);
144
+ return signoff && draft && {kind: 'parts', accepted_parts: {signoff_at: signoff.at, evidence: signoff.evidence},
145
+ structure: signoff.structure, draft_id: draft.id, parts: draft.parts};
146
+ }
147
+ const signoff = approval(project, 'rig-review', at);
148
+ const rig = records(project.versions).filter(v => v.kind === 'rig' && date(v.at) <= at &&
149
+ !reopened(project, 'rig-review', date(v.at) - 1, at) &&
150
+ records(v.verdicts).filter(d => d.review === 'rig-review' && d.by !== 'agent' && date(d.at) <= at &&
151
+ d.verdict !== 'provisional').at(-1)?.verdict === 'accepted').sort((a, b) => Number(b.n) - Number(a.n))[0];
152
+ const draft = rig && draftFor(project, approval(project, 'parts-review', date(rig.at)), date(rig.at));
153
+ return signoff && rig && draft && {kind: 'rig', rig_version: rig.n, signoff_at: signoff.at,
154
+ config: object(rig.provenance).config, parts: draft.parts};
155
+ }
156
+
157
+ function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean) {
158
+ const drafted = date(set.drafted_at);
159
+ const ctx = object(raw.context);
160
+ const expected = contextAt(project, set.stage, drafted);
161
+ const historicalInputs = !fresh && set.stage === 'interview';
162
+ const matches = historicalInputs ? ctx.kind === 'inputs' && records(ctx.files).length > 0 &&
163
+ records(ctx.files).every(file => records(object(expected).files).some(declared => equal(declared, file))) :
164
+ equal(expected, ctx) && equal(contextAt(project, set.stage, at), ctx);
165
+ if (!Number.isFinite(at) || drafted > at || !matches || reopened(project, set.stage, drafted, at)) return stale(set.id);
166
+ const parts = object(ctx.parts);
167
+ const fileRefs = records(ctx.kind === 'inputs' ? ctx.files : parts.files).map(binding);
168
+ const extra = ctx.kind === 'parts' ? [ctx.structure, object(ctx.accepted_parts).evidence] : ctx.kind === 'rig' ? [ctx.config] : [];
169
+ const images: Image[] = [];
170
+ try {
171
+ if (!fileRefs.length || new Set(fileRefs.map(ref => ref.path)).size !== fileRefs.length) throw new Error('Invalid inventory');
172
+ let partsUnavailable = false;
173
+ for (const ref of [...fileRefs, ...extra.map(binding)]) {
174
+ try {boundBytes(root, ref);}
175
+ catch (error) {
176
+ if (fresh || !ref.path.startsWith('derived/drafts/') || (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
177
+ partsUnavailable = true;
178
+ }
179
+ }
180
+ if (partsUnavailable) return {images, hasParts:true, partsUnavailable};
181
+ const add = (ref: SetRef, name: string) => {
182
+ const type = ({'.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.webp':'image/webp','.svg':'image/svg+xml'} as Record<string, string>)[extname(ref.path).toLowerCase()];
183
+ if (type) images.push({ref, name, type});
184
+ };
185
+ if (ctx.kind === 'inputs') {
186
+ for (const ref of fileRefs) add(ref, ref.path.split('/').at(-1)!);
187
+ } else {
188
+ if (!literalPath(parts.path)) throw new Error('Invalid parts directory');
189
+ const manifest = fileRefs.find(ref => ref.path === parts.path + '/parts.json');
190
+ if (!manifest) throw new Error('Missing bound parts.json');
191
+ for (const part of records(jsonObject(boundBytes(root, manifest)).parts)) {
192
+ if (!text(part.name)) throw new Error('Invalid part name');
193
+ const file = fileRefs.find(ref => ref.path === parts.path + '/parts/' + part.name + '.png');
194
+ if (!file) throw new Error('Missing bound part image');
195
+ add(file, part.name);
196
+ }
197
+ }
198
+ } catch { return stale(set.id + ' context files'); }
199
+ return {images, hasParts: ctx.kind !== 'inputs'};
200
+ }
201
+
202
+ export function readProject(root: string, now = Date.now()) {
203
+ try {
204
+ root = realpathSync(resolve(root));
205
+ if (!lstatSync(root).isDirectory()) return invalid('Project root must be a directory');
206
+ } catch {return invalid('Project root must be a readable directory');}
207
+ let bytes: Buffer;
208
+ let project: RecordData;
209
+ try {
210
+ bytes = readRegular(checkedPath(root, 'project.json'), 8 * 1024 * 1024);
211
+ project = jsonObject(bytes);
212
+ } catch {return invalid('project.json must be a readable regular JSON file');}
213
+ if (project.schema !== 'rig-create/project@0') return invalid('Unsupported create project');
214
+ const interview = object(project.interview);
215
+ const questions: InterviewQuestion[] = [];
216
+ const historical: HistoricalInterview[] = [];
217
+ const seen = new Map<string, string>();
218
+ for (const [items, answerKey, allowed] of [
219
+ [interview.framing, 'answer', ['interview']],
220
+ [interview.waypoints, 'guide', optionStages.slice(0, 2)],
221
+ [object(interview.post).items, 'guide', ['post-interview']],
222
+ ] as const) {
223
+ for (const item of records(items)) {
224
+ const current = object(item[answerKey]);
225
+ const answers = [current, ...records(item.history)];
226
+ for (const answer of answers) {
227
+ if (typeof item.id === 'string' && typeof answer.verbatim === 'string' && answer.choice === undefined) {
228
+ historical.push({question:item.id, verbatim:answer.verbatim,
229
+ by:typeof answer.by === 'string' ? answer.by : undefined, at:typeof answer.at === 'string' ? answer.at : undefined});
230
+ }
231
+ }
232
+ const entries = [
233
+ ...(item.pending_options === undefined ? [] : [{ref: item.pending_options, answer: undefined}]),
234
+ ...answers.filter(answer => object(answer.choice).spec === 'rig-create/interview-choice@1')
235
+ .map(answer => ({ref: object(answer.choice).set, answer})),
236
+ ];
237
+ for (const entry of entries) {
238
+ const ref = binding(entry.ref);
239
+ const prior = seen.get(ref.sha256);
240
+ if (prior !== undefined) {
241
+ if (prior !== ref.path) return invalid('A retained set hash has conflicting paths');
242
+ continue;
243
+ }
244
+ const raw = readSet(root, ref);
245
+ const expectedStage = allowed.length === 1 ? allowed[0]! :
246
+ ['rig_type','reference','seethrough','assemble'].includes(String(item.id)) ? 'interview' : 'rigging-interview';
247
+ const set = validateSet(raw, item.id, [expectedStage]);
248
+ const editable = entry.answer === undefined;
249
+ if (editable && (object(interview.order).spec !== 'rig-create/stage-order@2' || !Number.isFinite(date(object(interview.order).choices_adopted_at)))) {
250
+ throw new Error('INTERVIEW_CHOICE_REQUIRED: Adopt create choices before selecting');
251
+ }
252
+ if (editable && approval(project, set.stage === 'interview' ? 'plan-approved' : set.stage, now)) return invalid('Question approval is still live');
253
+ const context = inspectContext(root, project, raw, set, editable ? now : date(entry.answer?.at), editable);
254
+ questions.push({ref, set, editable, answer: entry.answer, ...context});
255
+ seen.set(ref.sha256, ref.path);
256
+ }
257
+ }
258
+ }
259
+ return {root, hash: digest(bytes), project, questions, historical};
260
+ }
@@ -0,0 +1,96 @@
1
+ import { lstatSync } from 'node:fs';
2
+ import { accessGate } from './open-protocol.ts';
3
+ import { boundBytes, invalid, object, readProject } from './interview-project.ts';
4
+ import { outputDirectory, picksLimit, readPicks, savePicks } from './interview-picks.ts';
5
+
6
+ export const interviewHeaders = {
7
+ 'Cache-Control':'no-store', 'X-Content-Type-Options':'nosniff',
8
+ 'Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
9
+ };
10
+ const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
11
+ const json = (value: unknown, status = 200) => Response.json(value, {status, headers:interviewHeaders});
12
+
13
+ async function body(req: Request) {
14
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type') ?? '')) return invalid('Expected application/json');
15
+ const reader = req.body?.getReader();
16
+ if (!reader) return invalid('Missing body');
17
+ const chunks: Uint8Array[] = [];
18
+ let bytes = 0;
19
+ try {
20
+ for (;;) {
21
+ const {value, done} = await reader.read();
22
+ if (done) break;
23
+ bytes += value.length;
24
+ if (bytes > picksLimit) {
25
+ await reader.cancel().catch(() => {});
26
+ return invalid('Picks payload exceeds size limit');
27
+ }
28
+ chunks.push(value);
29
+ }
30
+ return JSON.parse(new TextDecoder('utf-8', {fatal:true}).decode(Buffer.concat(chunks)));
31
+ } catch {return invalid('Invalid or oversized picks JSON');}
32
+ finally {reader.releaseLock();}
33
+ }
34
+
35
+ export function interviewRoutes(root: string, output: string, capability: string) {
36
+ const opened = readProject(root);
37
+ const outputPath = outputDirectory(opened.root, output, opened.project);
38
+ const openedOutput = lstatSync(outputPath);
39
+ const destination = () => {
40
+ const path = outputDirectory(opened.root, output, opened.project);
41
+ const info = lstatSync(path);
42
+ if (info.dev !== openedOutput.dev || info.ino !== openedOutput.ino) throw new Error('INTERVIEW_PICKS_OUTPUT: Output directory changed');
43
+ return path;
44
+ };
45
+ const current = () => {
46
+ if (readProject(opened.root).hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
47
+ };
48
+ return async (req: Request, origin: string): Promise<Response | undefined> => {
49
+ const url = new URL(req.url);
50
+ if (url.origin !== origin) return json({error:'Loopback host required'}, 403);
51
+ const denied = accessGate(req, capability);
52
+ if (denied) return denied;
53
+ try {
54
+ if (req.method === 'GET' && url.pathname === '/api/interview') {
55
+ current();
56
+ const dir = destination();
57
+ return json({historical:opened.historical, questions:opened.questions.map(question => ({
58
+ ...question, saved:question.editable ? readPicks(dir, question) : null,
59
+ images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
60
+ }))});
61
+ }
62
+ const image = /^\/api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(url.pathname);
63
+ if (image && req.method === 'GET') {
64
+ current();
65
+ const asset = opened.questions.find(question => question.ref.sha256 === image[1])?.images[Number(image[2])];
66
+ if (!asset) return json({error:'Not found'}, 404);
67
+ let bytes: Buffer;
68
+ try {bytes = boundBytes(opened.root, asset.ref);}
69
+ catch {throw new Error('INTERVIEW_OPTIONS_STALE: Image bytes changed');}
70
+ if (asset.type === 'image/png' && !bytes.subarray(0, pngSignature.length).equals(pngSignature)) {
71
+ return json({error:'INTERVIEW_IMAGE_INVALID'}, 422);
72
+ }
73
+ return new Response(new Uint8Array(bytes), {headers:{...interviewHeaders,
74
+ 'Content-Type':asset.type, 'Content-Security-Policy':"default-src 'none'; sandbox"}});
75
+ }
76
+ if (url.pathname === '/api/interview/picks' && req.method === 'POST') {
77
+ if (req.headers.get('origin') !== origin) return json({error:'Same-origin Origin required'}, 403);
78
+ const input = await body(req);
79
+ current();
80
+ const ref = object(object(input).set);
81
+ const question = opened.questions.find(question => question.editable && question.ref.path === ref.path && question.ref.sha256 === ref.sha256);
82
+ if (!question) {
83
+ if (opened.questions.some(question => question.ref.path === ref.path)) {
84
+ throw new Error('INTERVIEW_OPTIONS_STALE: Displayed set is changed or superseded');
85
+ }
86
+ return invalid('Displayed set is not registered');
87
+ }
88
+ return json(savePicks(destination(), question, input));
89
+ }
90
+ } catch (error) {
91
+ const message = error instanceof Error ? error.message : '';
92
+ const code = /^INTERVIEW_[A-Z_]+:/.exec(message)?.[0].slice(0,-1) ?? 'INTERVIEW_CHOICE_INVALID';
93
+ return json({error:code}, code === 'INTERVIEW_OPTIONS_STALE' ? 409 : 400);
94
+ }
95
+ };
96
+ }
@@ -0,0 +1,55 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { appRoot } from './build.ts';
4
+ import { createLiveLifecycle, LIVE_PATH } from './live-lifecycle.ts';
5
+ import { interviewHeaders, interviewRoutes } from './interview-routes.ts';
6
+
7
+ export async function startInterviewServer(root: string, output: string, port: number, exitOnClose = false) {
8
+ const capability = randomBytes(32).toString('hex');
9
+ const route = interviewRoutes(root, output, capability);
10
+ const bundle = await Bun.build({entrypoints:[appRoot + 'web/interview.ts'], target:'browser', format:'esm'});
11
+ if (!bundle.success || !bundle.outputs[0]) throw new Error('Interview frontend bundle failed');
12
+ const [html, css] = await Promise.all(['interview.html','interview.css'].map(path => readFile(appRoot + 'web/' + path)));
13
+ const live = createLiveLifecycle({label:'review interview', exitOnClose, stopServer:() => server.stop(true)});
14
+ const server = Bun.serve({hostname:'127.0.0.1', port, websocket:live.websocket, async fetch(req, srv) {
15
+ const origin = 'http://127.0.0.1:' + srv.port;
16
+ const {pathname} = new URL(req.url);
17
+ if (pathname === LIVE_PATH && req.method === 'GET') {
18
+ if (req.headers.get('origin') !== origin) return new Response(null, {status:403});
19
+ return live.upgrade(req, srv, interviewHeaders);
20
+ }
21
+ live.onRequestStart(pathname);
22
+ try {
23
+ const response = await route(req, origin);
24
+ if (response) return response;
25
+ const files = new Map([
26
+ ['/', [html, 'text/html; charset=utf-8']],
27
+ ['/interview.css', [css, 'text/css']],
28
+ ['/interview.js', [bundle.outputs[0], 'text/javascript']],
29
+ ] as const);
30
+ const file = req.method === 'GET' ? files.get(pathname as '/' | '/interview.css' | '/interview.js') : undefined;
31
+ return file ? new Response(file[0] as BodyInit, {headers:{...interviewHeaders,'Content-Type':file[1]}}) :
32
+ new Response(null, {status:404, headers:interviewHeaders});
33
+ } finally {live.onRequestEnd(pathname);}
34
+ }});
35
+ return {url:'http://127.0.0.1:' + server.port + '/#cap=' + capability, stop:() => {live.stop(); server.stop(true);}};
36
+ }
37
+
38
+ export const interviewUsage = 'Usage: rig-review interview <create-root> --picks-dir <project-relative directory> [--port <n>]';
39
+ export async function interviewCommand(args: string[]) {
40
+ if (!args.length || args[0] === '--help' || args[0] === '-h') {console.log(interviewUsage); return;}
41
+ const root = args.shift()!;
42
+ let output: string | undefined;
43
+ let port: number | undefined;
44
+ while (args.length) {
45
+ const flag = args.shift();
46
+ const value = args.shift();
47
+ if (flag === '--picks-dir' && value && output === undefined) output = value;
48
+ else if (flag === '--port' && value && /^\d+$/.test(value) && Number(value) <= 65535 && port === undefined) port = Number(value);
49
+ else throw new Error(interviewUsage);
50
+ }
51
+ if (!output) throw new Error(interviewUsage);
52
+ const running = await startInterviewServer(root, output, port ?? 4317, true);
53
+ console.log(running.url);
54
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) process.once(signal, () => running.stop());
55
+ }
package/src/parts-view.ts CHANGED
@@ -608,3 +608,12 @@ export async function partsDifference(pkg:PartsViewPackage,index:number,threshol
608
608
  const result=differencePixels(part,item!,painting,fronts,threshold,footprints);
609
609
  await assertPartsUnchanged(pkg);return result;
610
610
  }
611
+
612
+ /** Selected JSON keeps the canonical verdict and names the user's handoff selection. */
613
+ export function exportPartsCorrection(verdict:PartsVerdict, correction:ReturnType<typeof import('./correction-handoff.ts').projectPartsDescription>):string {
614
+ return JSON.stringify({...verdict,correction:{
615
+ path:'described',stage:correction.stage,itemId:correction.itemId,part:correction.part,
616
+ verbatim:correction.verbatim,selectorArgs:correction.on,outcome:null,
617
+ ...('imageHash' in correction?{imageHash:correction.imageHash}:{}),
618
+ }},null,2)+'\n';
619
+ }