rig-review 1.10.2 → 1.12.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/docs/PARTS_VIEW.md +5 -0
- package/docs/REVIEW_PACKAGE.md +53 -2
- package/docs/WORKFLOWS.md +63 -0
- package/package.json +1 -1
- package/src/cli.ts +47 -10
- package/src/correction-handoff.ts +186 -0
- package/src/direction-inspection.ts +65 -0
- package/src/feedback-export.ts +14 -0
- package/src/handoff.ts +12 -2
- package/src/interview-picks.ts +89 -0
- package/src/interview-project.ts +260 -0
- package/src/interview-routes.ts +96 -0
- package/src/interview-server.ts +55 -0
- package/src/manifest.ts +16 -4
- package/src/open.ts +1 -1
- package/src/parts-view.ts +9 -0
- package/src/rebuild.ts +114 -21
- package/src/server.ts +19 -3
- package/src/session.ts +4 -2
- package/src/strip-render.ts +5 -2
- package/web/catalog-en.ts +70 -2
- package/web/catalog-ko.ts +70 -2
- package/web/direction-panel.ts +88 -0
- package/web/index.html +1 -1
- package/web/interview-panel.ts +180 -0
- package/web/interview.css +26 -0
- package/web/interview.html +17 -0
- package/web/interview.ts +27 -0
- package/web/main.ts +106 -13
- package/web/parts.html +1 -1
- package/web/parts.ts +2 -1
- package/web/stage-nav.ts +14 -7
- package/web/styles.css +3 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { closeSync, lstatSync, openSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { isDeepStrictEqual as equal } from 'node:util';
|
|
5
|
+
import { checkedPath, invalid, jsonObject, object, readRegular, type InterviewQuestion, type SetRef } from './interview-project.ts';
|
|
6
|
+
|
|
7
|
+
export const picksLimit = 256 * 1024;
|
|
8
|
+
interface Pick {ask: string; option_id: string; other_text?: string}
|
|
9
|
+
export interface Picks {schema: 'rig-review/interview-picks@1'; set: SetRef; picks: Pick[]; note?: string; by: 'user'; at: string}
|
|
10
|
+
|
|
11
|
+
export function validatePicks(input: unknown, question: InterviewQuestion): Picks {
|
|
12
|
+
const data = object(input);
|
|
13
|
+
if (data.schema !== 'rig-review/interview-picks@1' || data.by !== 'user' ||
|
|
14
|
+
typeof data.at !== 'string' || !Number.isFinite(Date.parse(data.at)) || Date.parse(data.at) > Date.now() ||
|
|
15
|
+
Date.parse(data.at) < Date.parse(question.set.drafted_at) ||
|
|
16
|
+
(data.note !== undefined && typeof data.note !== 'string') ||
|
|
17
|
+
Object.keys(data).some(key => !['schema','set','picks','note','by','at'].includes(key)) ||
|
|
18
|
+
!Array.isArray(data.picks) || data.picks.length !== question.set.asks.length) return invalid('Invalid picks payload');
|
|
19
|
+
if (!equal(data.set, question.ref)) return invalid('Displayed set is not registered');
|
|
20
|
+
const choices = question.set.asks.map((ask, index) => {
|
|
21
|
+
const pick = object((data.picks as unknown[])[index]);
|
|
22
|
+
const option = ask.options.find(option => option.id === pick.option_id);
|
|
23
|
+
if (!option || pick.ask !== ask.id || Object.keys(pick).some(key => !['ask','option_id','other_text'].includes(key)) ||
|
|
24
|
+
(option.kind === 'other' ? typeof pick.other_text !== 'string' || !pick.other_text.trim() : 'other_text' in pick)) return invalid('Invalid ordered pick');
|
|
25
|
+
return option;
|
|
26
|
+
});
|
|
27
|
+
if (question.set.assembly.rule === 'merge') {
|
|
28
|
+
const keys = choices.flatMap(option => Object.keys(object(option.fragment)));
|
|
29
|
+
if (new Set(keys).size !== keys.length) return invalid('Merge key collision');
|
|
30
|
+
}
|
|
31
|
+
for (const constraint of question.set.constraints ?? []) {
|
|
32
|
+
const tuple = constraint.asks.map(id => choices[question.set.asks.findIndex(ask => ask.id === id)]);
|
|
33
|
+
if (tuple.every(option => option?.kind === 'value') && !constraint.allowed.some(allowed => equal(allowed, tuple.map(option => option?.id)))) {
|
|
34
|
+
throw new Error('INTERVIEW_CHOICE_CONSTRAINT: Pick an allowed combination');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return data as unknown as Picks;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function outputDirectory(root: string, path: string, project: unknown): string {
|
|
41
|
+
const fail = () => { throw new Error('INTERVIEW_PICKS_OUTPUT: Choose a dedicated existing project-relative output directory'); };
|
|
42
|
+
if (['.git','node_modules'].includes(path.split('/')[0]!)) return fail();
|
|
43
|
+
const portable = (value: string) => value.normalize('NFC').toLowerCase();
|
|
44
|
+
const output = portable(path);
|
|
45
|
+
const check = (value: unknown): void => {
|
|
46
|
+
if (typeof value === 'string') {
|
|
47
|
+
const input = portable(value);
|
|
48
|
+
if (input === output || input.startsWith(output + '/') || output.startsWith(input + '/')) fail();
|
|
49
|
+
}
|
|
50
|
+
if (value && typeof value === 'object') Object.values(value).forEach(check);
|
|
51
|
+
};
|
|
52
|
+
check(project);
|
|
53
|
+
try {return checkedPath(root, path, true);} catch {return fail();}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function target(directory: string, question: InterviewQuestion) {
|
|
57
|
+
return join(directory, question.ref.sha256 + '.json');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function readPicks(directory: string, question: InterviewQuestion): Picks | null {
|
|
61
|
+
const path = target(directory, question);
|
|
62
|
+
try {
|
|
63
|
+
const entry = lstatSync(path);
|
|
64
|
+
if (!entry.isFile() || entry.nlink !== 1) throw new Error('Output is aliased');
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
|
|
67
|
+
throw new Error('INTERVIEW_PICKS_OUTPUT: Output is aliased or inaccessible');
|
|
68
|
+
}
|
|
69
|
+
try { return validatePicks(jsonObject(readRegular(path, picksLimit)), question); }
|
|
70
|
+
catch {throw new Error('INTERVIEW_PICKS_OUTPUT: Existing file is not a valid picks record for this set');}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function savePicks(directory: string, question: InterviewQuestion, input: unknown): Picks {
|
|
74
|
+
const picks = validatePicks(input, question);
|
|
75
|
+
readPicks(directory, question);
|
|
76
|
+
const bytes = JSON.stringify(picks) + '\n';
|
|
77
|
+
if (Buffer.byteLength(bytes) > picksLimit) return invalid('Picks file exceeds size limit');
|
|
78
|
+
const temp = join(directory, '.interview-' + randomUUID() + '.tmp');
|
|
79
|
+
const fd = openSync(temp, 'wx', 0o600);
|
|
80
|
+
try {
|
|
81
|
+
try {writeFileSync(fd, bytes);}
|
|
82
|
+
finally {closeSync(fd);}
|
|
83
|
+
renameSync(temp, target(directory, question));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
unlinkSync(temp);
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
return picks;
|
|
89
|
+
}
|
|
@@ -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/manifest.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {DIRECTION_MAX_BYTES, readDirectionInspection, type DirectionInspection} from './direction-inspection.ts';
|
|
1
2
|
import {discoverTurnDials} from './turn-pad.ts';
|
|
2
3
|
import { createHash } from 'node:crypto';
|
|
3
4
|
import { toolVersions } from './versions.ts';
|
|
@@ -14,6 +15,7 @@ export interface Reference { id: string; label: string; type: 'image' | 'video'
|
|
|
14
15
|
export interface Checkpoint { id: string; title: string; time?: number; animation?: string; reference?: string; note?: string; workspace?: 'modeling' | 'motion'; camera?: { zoom: number; x: number; y: number }; axis?: {id:string;value:number} }
|
|
15
16
|
export interface ReviewManifest {
|
|
16
17
|
schema: 'rig-review/1'; id: string; title: string; revision: string; model?: string; motion?: string;
|
|
18
|
+
direction?: string; sets?: string;
|
|
17
19
|
references: Reference[]; animations: { id: string; label?: string; duration?: number }[];
|
|
18
20
|
checkpoints: Checkpoint[]; authoring: { label: string; path: string }[];
|
|
19
21
|
axes: { id: string; label: string; animation: string; min: number; max: number }[];
|
|
@@ -22,7 +24,7 @@ export interface ReviewManifest {
|
|
|
22
24
|
producer?: HandoffDeclaration;
|
|
23
25
|
}
|
|
24
26
|
export interface ReviewedSource { readonly packageRevision:string; readonly viewerVersion:string; readonly runtimeVersion:string; readonly rig:{readonly path:string;readonly sha256:string}|null; readonly motion:{readonly path:string;readonly sha256:string}|null; readonly handoff?:HandoffRecord }
|
|
25
|
-
export interface ReviewPackage { referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
|
|
27
|
+
export interface ReviewPackage { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
|
|
26
28
|
/** The resolved producer handoff (#101) and, when there is none, the refusal line naming where it was looked for. */
|
|
27
29
|
handoff: Handoff|null; handoffReason: string|null; handoffInputs?: HandoffFlags;
|
|
28
30
|
/** #187: the rig-parts build root ({@link isBuildRoot}) whose `check/` this package is, however it was opened; review state stays outside it. */
|
|
@@ -37,6 +39,7 @@ export function string(value: unknown, field: string): string { if (typeof value
|
|
|
37
39
|
function id(value: unknown, field: string): string { const s = string(value, field); if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(s)) fail(field, 'identifier [A-Za-z0-9][A-Za-z0-9._-], at most 128 characters'); return s; }
|
|
38
40
|
export function choice<T extends string>(value: unknown, choices: readonly T[], field: string): T { if (!choices.includes(value as T)) fail(field, choices.join(' | ')); return value as T; }
|
|
39
41
|
function number(value: unknown, field: string, min = 0): number { if (typeof value !== 'number' || !Number.isFinite(value) || value < min) fail(field, `finite number >= ${min}`); return value; }
|
|
42
|
+
export { number as numberField };
|
|
40
43
|
function optionalString(value: unknown, field: string): string | undefined { return value === undefined ? undefined : string(value, field); }
|
|
41
44
|
function optionalNumber(value: unknown, field: string): number | undefined { return value === undefined ? undefined : number(value, field); }
|
|
42
45
|
function list<T>(value: unknown, field: string, parse: (v: Record<string, unknown>, field: string) => T): T[] {
|
|
@@ -62,6 +65,8 @@ export function parseManifest(input: unknown): ReviewManifest {
|
|
|
62
65
|
const manifest: ReviewManifest = {
|
|
63
66
|
schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
|
|
64
67
|
model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
|
|
68
|
+
...(m.direction===undefined?{}:{direction:packagePath(m.direction,'direction')}),
|
|
69
|
+
...(m.sets===undefined?{}:{sets:packagePath(m.sets,'sets')}),
|
|
65
70
|
motion:m.motion===undefined?undefined:packagePath(m.motion,'motion'),
|
|
66
71
|
references: list(m.references, 'references', (v,f) => ({ id:id(v.id,f+'.id'), label:string(v.label,f+'.label'), type:choice(v.type,['image','video','pose'],f+'.type'), path:packagePath(v.path,f+'.path'), width:v.width===undefined?undefined:number(v.width,f+'.width',Number.EPSILON), height:v.height===undefined?undefined:number(v.height,f+'.height',Number.EPSILON) })),
|
|
67
72
|
animations: list(m.animations,'animations',(v,f) => ({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),duration:optionalNumber(v.duration,f+'.duration')})),
|
|
@@ -72,6 +77,8 @@ export function parseManifest(input: unknown): ReviewManifest {
|
|
|
72
77
|
audio:{clips:list(audio.clips,'audio.clips',(v,f)=>({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),cues:list(audio.cues,'audio.cues',(v,f)=>({id:id(v.id,f+'.id'),clip:string(v.clip,f+'.clip'),time:number(v.time,f+'.time'),animation:optionalString(v.animation,f+'.animation')}))}
|
|
73
78
|
};
|
|
74
79
|
if(manifest.model&&!manifest.model.endsWith('.model.json'))fail('model','compiled model path ending .model.json (the play runtime input)');
|
|
80
|
+
if(manifest.sets&&!manifest.model)fail('sets','compiled model declaration');
|
|
81
|
+
if(manifest.direction&&!manifest.model)fail('direction','compiled model declaration');
|
|
75
82
|
for (const c of manifest.checkpoints) { if(c.reference && !manifest.references.some(r=>r.id===c.reference)) fail(`checkpoint ${c.id}.reference`,'declared reference id'); if(c.animation && !manifest.animations.some(a=>a.id===c.animation)) fail(`checkpoint ${c.id}.animation`,'declared animation id'); }
|
|
76
83
|
for (const c of manifest.audio.cues) { if(!manifest.audio.clips.some(a=>a.id===c.clip)) fail(`cue ${c.id}.clip`,'declared audio clip id'); if(c.animation && !manifest.animations.some(a=>a.id===c.animation)) fail(`cue ${c.id}.animation`,'declared animation id'); }
|
|
77
84
|
for (const a of manifest.axes) { if(a.min >= a.max) fail(`axis ${a.id}`,'min < max'); if(!manifest.animations.some(v=>v.id===a.animation)) fail(`axis ${a.id}.animation`,'declared animation id'); }
|
|
@@ -87,6 +94,8 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
|
|
|
87
94
|
const manifestPath=inputPath;const root=directory?inputPath:await realpath(dirname(inputPath));
|
|
88
95
|
const manifest=directory?await folderManifest(root):parseManifest(JSON.parse(await readFile(manifestPath,'utf8')));
|
|
89
96
|
const files = new Set([...(directory?[]:[relative(root,manifestPath)]),...manifest.references.map(v=>v.path),...manifest.authoring.map(v=>v.path),...manifest.audio.clips.map(v=>v.path)]);
|
|
97
|
+
if(manifest.direction)files.add(manifest.direction);
|
|
98
|
+
if(manifest.sets)files.add(manifest.sets);
|
|
90
99
|
const rootFile=async(name:string):Promise<string|undefined>=>{try{await safeFile(root,name);return name;}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return undefined;throw e;}};
|
|
91
100
|
const authoringPath=(name:string):string|undefined=>{const paths=manifest.authoring.filter(v=>posix.basename(v.path)===name);return paths.length===1?paths[0].path:undefined;};
|
|
92
101
|
const rigPath=manifest.model??await rootFile('skeleton.json')??authoringPath('skeleton.json')??await rootFile('skeleton.skel')??authoringPath('skeleton.skel');
|
|
@@ -107,23 +116,26 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
|
|
|
107
116
|
const joints=list(pose.joints,`pose ${r.id}.joints`,(v,f)=>({id:id(v.id,f+'.id'),x:number(v.x,f+'.x',-Number.MAX_VALUE),y:number(v.y,f+'.y',-Number.MAX_VALUE),parent:optionalString(v.parent,f+'.parent')}));
|
|
108
117
|
for(const j of joints) if(j.parent&&!joints.some(v=>v.id===j.parent&&v.id!==j.id)) fail(`pose ${r.id} joint ${j.id}.parent`,'another declared joint id');
|
|
109
118
|
}
|
|
110
|
-
const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let modelMetadata:Record<string,unknown>|null=null;
|
|
119
|
+
const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let modelMetadata:Record<string,unknown>|null=null;let directionInput:unknown;
|
|
111
120
|
// The handoff files are hashed beside the package: their record joins the reviewed identity (and so the session file).
|
|
112
121
|
const {handoff,reason:handoffReason}=await resolveHandoff(root,manifest.producer,options.handoff);
|
|
113
122
|
// #329: the source painting the handoff knows is the first reference, outside the package's own files.
|
|
114
123
|
const painting=sourcePainting(manifest,handoff,directory);
|
|
115
124
|
const hash = createHash('sha256');hash.update(JSON.stringify(manifest));hash.update('\0');const fileHashes=new Map<string,string>();
|
|
116
|
-
for(const p of [...files].sort()) { const full=await safeFile(root,p); const before=await stat(full); hash.update(p);hash.update('\0');hash.update(String(before.size));hash.update('\0'); const fileHash=createHash('sha256');const metadataChunks:Buffer[]=[];
|
|
125
|
+
for(const p of [...files].sort()) { const full=await safeFile(root,p); const before=await stat(full); hash.update(p);hash.update('\0');hash.update(String(before.size));hash.update('\0'); const fileHash=createHash('sha256');const metadataChunks:Buffer[]=[];const isDirection=p===manifest.direction;let bytesRead=0;
|
|
126
|
+
if(isDirection&&before.size>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(isDirection&&(bytesRead+=chunk.length)>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');if(p===reportPath||p===manifest.model||isDirection)metadataChunks.push(chunk);}fileHashes.set(p,fileHash.digest('hex')); const after=await stat(full); if(before.size!==after.size||before.mtimeMs!==after.mtimeMs) throw new Error(`Asset ${p} changed while hashing; retry with stable package inputs`);
|
|
117
127
|
// The parser and package hash consume the same bytes, never two file reads.
|
|
118
128
|
if(p===manifest.model){if(fileHashes.get(p)!==modelBytesHash)throw new Error(`Model ${p} changed while hashing; retry with stable package inputs`);modelMetadata=object(JSON.parse(Buffer.concat(metadataChunks).toString('utf8')),'model');}
|
|
129
|
+
if(isDirection)directionInput=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));
|
|
119
130
|
if(p===reportPath){let value:unknown;try{value=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));}catch(e){throw new Error(`${p}: ${e instanceof Error?e.message:String(e)}`);}report=parseReport(value,p);}
|
|
120
131
|
}
|
|
121
132
|
if(painting){hash.update(SOURCE_PAINTING_ID);hash.update('\0');hash.update(painting.sha256);hash.update('\0');}
|
|
122
133
|
// #192: the root is `check/` whether the folder or its review.json was opened, so the build root is kept either way.
|
|
123
134
|
const buildRoot=basename(root)==='check'&&await isBuildRoot(dirname(root))?dirname(root):undefined;
|
|
124
135
|
const reviewedSource:ReviewedSource={packageRevision:manifest.revision,...await toolVersions(),rig:rigPath?{path:rigPath,sha256:fileHashes.get(rigPath)!}:null,motion:motionPath?{path:motionPath,sha256:fileHashes.get(motionPath)!}:null,...(handoff?{handoff:handoff.record}:{})};
|
|
136
|
+
const direction=manifest.direction?readDirectionInspection(directionInput,{path:manifest.direction,sha256:fileHashes.get(manifest.direction)!},reviewedSource.rig):undefined;
|
|
125
137
|
const feedbackCatalog:FeedbackCatalog={rig:manifest.id,bones:modelNames(modelMetadata,'bones'),slots:modelNames(modelMetadata,'slots'),animations:modelAnimations(modelMetadata),clock:report?.clock??null,clockAnimation:report?.animation??null,...(discoverTurnDials(modelMetadata).length?{turnDials:discoverTurnDials(modelMetadata)}:{})};
|
|
126
|
-
return {referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{})};
|
|
138
|
+
return {...(direction?{direction}:{}),...(manifest.sets?{setsHash:fileHashes.get(manifest.sets)!}:{}),referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{})};
|
|
127
139
|
}
|
|
128
140
|
|
|
129
141
|
/** #329: the reference id and served path of the handoff's source painting; the path is a name, never a package file. */
|
package/src/open.ts
CHANGED
|
@@ -108,7 +108,7 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
|
|
|
108
108
|
}
|
|
109
109
|
async function verifyOpenLoad(p:OpenPackage,viewOnly:boolean,cwd=process.cwd()):Promise<void>{
|
|
110
110
|
if(p.mode==='single'){
|
|
111
|
-
try{await verifyCompiledModel(p.p.root,p.p.manifest.model,p.selection?.name);}
|
|
111
|
+
try{await verifyCompiledModel(p.p.root,p.p.manifest.model,p.selection?.name,p.p.manifest.sets);}
|
|
112
112
|
catch(error){throw new Error(`OPEN_MODEL_UNAVAILABLE: ${error instanceof Error?error.message:String(error)}`,{cause:error});}
|
|
113
113
|
const handoffReason=await verifyHandoffReadiness(p.p,[p.p.root,cwd],viewOnly);
|
|
114
114
|
if(handoffReason)throw new Error(`OPEN_MODEL_UNAVAILABLE: ${handoffReason}`);
|
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
|
+
}
|