rig-review 2.4.4 → 2.4.6

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.
@@ -1019,6 +1019,22 @@ and standalone parts retain their existing inspection surfaces.
1019
1019
 
1020
1020
  In the standing live-job contract ([Review #484](https://github.com/rig-c/review/issues/484)), direction carriage is metadata-only (`source.direction` and the `direction-review` stage on `review-verdict`). That metadata carriage is distinct from [Review #482](https://github.com/rig-c/review/issues/482) preview and [Review #483](https://github.com/rig-c/review/issues/483) actual plated take playback, while [Review #373](https://github.com/rig-c/review/issues/373) remains parked.
1021
1021
 
1022
+ ### Scene interview records
1023
+
1024
+ The interview reader supports the scene option codec and dated currentness in
1025
+ Create's merged [PROJECT contract](https://github.com/rig-c/create/blob/f1868eeeed2dcc6b792c230a8bf93117a05edcd5/docs/PROJECT.md#scene-option-context).
1026
+ It checks every historical answer and completed decision at its own time and
1027
+ retains original words, source, time and set bindings with named record issues.
1028
+ Pre-cutoff currentness-only exceptions display `INTERVIEW_OPTIONS_SCENE_LEGACY`
1029
+ without blocking the legacy interview. Full scene image and registration checks
1030
+ remain producer checks.
1031
+
1032
+ The temporary [#555 gate](https://github.com/rig-c/review/issues/555) refuses
1033
+ standing publication with `JOB_RECORD_INCOMPLETE` for scene answers, legacy
1034
+ warnings or historical record issues before publication lookup or snapshot
1035
+ writes. Named diagnostic carriage remains an unmet gate pending the signed
1036
+ job API@2 contract. An editable current scene can proceed to publication lookup.
1037
+
1022
1038
  ## Live job contract
1023
1039
 
1024
1040
  `src/job-contract.ts` defines the frozen semantic contract boundary for [Review #484](https://github.com/rig-c/review/issues/484), [Create #182](https://github.com/rig-c/create/issues/182), [Create #184](https://github.com/rig-c/create/issues/184), [Parts #1159](https://github.com/rig-c/parts/issues/1159) and [Parts #1163](https://github.com/rig-c/parts/issues/1163) under `JOB_API_SCHEMA` (`rig-review/job-api@2`) and `JOB_ACT_SCHEMA` (`rig-review/act@2`), implemented across the backend session/store (`src/job-store.ts`, `src/job-session.ts`, `src/job-source.ts`, `src/job-act.ts`, `src/job-api.ts`, `src/job-worker.ts`), standing loopback job front and browser window runtime (`src/job-front.ts`, `web/job-session.ts`), and `rig-review session` CLI (`src/entry.ts`, `src/job-cli.ts`). The public installed managed-host entry is `@rig-c/review/job-host` with frozen exports in [Public API stability](STABILITY.md#managed-owner-host), and Create's production publication reader and writer-owned sibling `fetch-act` readback remain pending [Create #184](https://github.com/rig-c/create/issues/184) (publishing a Create root containing `project.json` without a host `readPublished` callback refuses `JOB_SOURCE_UNRETAINABLE` with `CREATE_PUBLICATION_CONTRACT_UNAVAILABLE`). One-shot file-handoff workflows documented elsewhere in this reference remain preserved as legacy/history compatibility for existing callers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "2.4.4",
3
+ "version": "2.4.6",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';
3
3
  import { extname, join, resolve } from 'node:path';
4
4
  import { isDeepStrictEqual as equal } from 'node:util';
5
+ import {coveringChange, sceneAt} from './interview-scene.ts';
5
6
 
6
7
  type RecordData = Record<string, unknown>;
7
8
  export interface SetRef {path: string; sha256: string}
@@ -13,7 +14,14 @@ export interface InterviewSet {
13
14
  asks: Ask[]; assembly: {rule: 'single' | 'concat' | 'merge'}; constraints?: Constraint[];
14
15
  }
15
16
  interface Image {ref: SetRef; name: string; type: string}
16
- export interface HistoricalInterview {question: string; verbatim: string; by?: string; at?: string}
17
+ export interface HistoricalInterview {
18
+ question: string; verbatim: string; by?: string; at?: string;
19
+ ref?: SetRef; record?: string; answer?: RecordData;
20
+ }
21
+ export interface InterviewDiagnostic {
22
+ code: 'INTERVIEW_OPTIONS_STALE' | 'INTERVIEW_OPTIONS_SCENE_LEGACY';
23
+ question: string; record: string; ref: SetRef; at?: string;
24
+ }
17
25
  export interface InterviewQuestion {ref: SetRef; set: InterviewSet; editable: boolean; images: Image[]; hasParts: boolean; partsUnavailable?: boolean; answer?: RecordData}
18
26
  export const digest = (data: Buffer | string) => createHash('sha256').update(data).digest('hex');
19
27
  export const object = (v: unknown): RecordData => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as RecordData : {};
@@ -24,7 +32,6 @@ const invalidOptions = (message: string): never => {throw new Error('INTERVIEW_O
24
32
  const stale = (message: string): never => {throw new Error('INTERVIEW_OPTIONS_STALE: ' + message);};
25
33
  const text = (v: unknown): v is string => typeof v === 'string' && !!v.trim();
26
34
  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
35
  const optionStages = ['interview', 'rigging-interview', 'post-interview'];
29
36
 
30
37
  export function literalPath(path: unknown): path is string {
@@ -120,13 +127,7 @@ function validateSet(raw: RecordData, question: unknown, allowedStages: string[]
120
127
  return raw as unknown as InterviewSet;
121
128
  }
122
129
 
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
+ const reopened = coveringChange;
130
131
  function approval(project: RecordData, stage: string, at: number) {
131
132
  return records(project.signoffs).filter(s => s.stage === stage && (s.checkpoint === null || s.checkpoint === undefined) &&
132
133
  text(s.by) && s.by.toLowerCase() !== 'agent' && date(s.at) <= at &&
@@ -154,9 +155,30 @@ function contextAt(project: RecordData, stage: string, at: number): unknown {
154
155
  config: object(rig.provenance).config, parts: draft.parts};
155
156
  }
156
157
 
157
- function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean) {
158
+ function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean): {
159
+ images: Image[]; hasParts: boolean; partsUnavailable?: boolean; legacy?: boolean;
160
+ } {
158
161
  const drafted = date(set.drafted_at);
159
162
  const ctx = object(raw.context);
163
+ if (!Number.isFinite(at) || drafted > at || reopened(project, set.stage, drafted, at)) return stale(set.id);
164
+ if (ctx.kind === 'scene') {
165
+ if (set.stage !== 'post-interview') return stale(set.id);
166
+ let legacy = false;
167
+ let scene: RecordData = {};
168
+ for (const instant of [drafted, at]) {
169
+ const selected = sceneAt(project, instant, ref => jsonObject(boundBytes(root, ref)));
170
+ if (!selected || !equal(selected.context, ctx)) return stale(set.id);
171
+ if (!selected.current) {
172
+ if (drafted >= Date.parse('2026-11-08T00:00:00Z')) return stale(set.id);
173
+ legacy = true;
174
+ }
175
+ scene = selected.document;
176
+ }
177
+ const images = records(scene.plates).map(plate => ({
178
+ ref: {path: plate.path as string, sha256: plate.sha256 as string}, name: plate.role as string, type: 'image/png',
179
+ }));
180
+ return {images, hasParts: false, legacy};
181
+ }
160
182
  const expected = contextAt(project, set.stage, drafted);
161
183
  const historicalInputs = !fresh && set.stage === 'interview';
162
184
  const matches = historicalInputs ? ctx.kind === 'inputs' && records(ctx.files).length > 0 &&
@@ -214,13 +236,16 @@ export function readProject(root: string, now = Date.now()) {
214
236
  const interview = object(project.interview);
215
237
  const questions: InterviewQuestion[] = [];
216
238
  const historical: HistoricalInterview[] = [];
239
+ const diagnostics: InterviewDiagnostic[] = [];
240
+ let sceneAnswers = 0;
217
241
  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']],
242
+ for (const [items, answerKey, allowed, collection] of [
243
+ [interview.framing, 'answer', ['interview'], 'interview.framing'],
244
+ [interview.waypoints, 'guide', optionStages.slice(0, 2), 'interview.waypoints'],
245
+ [object(interview.post).items, 'guide', ['post-interview'], 'interview.post.items'],
222
246
  ] as const) {
223
- for (const item of records(items)) {
247
+ for (const [itemIndex, item] of records(items).entries()) {
248
+ const itemPath = `${collection}[${itemIndex}]`;
224
249
  const current = object(item[answerKey]);
225
250
  const answers = [current, ...records(item.history)];
226
251
  for (const answer of answers) {
@@ -230,31 +255,63 @@ export function readProject(root: string, now = Date.now()) {
230
255
  }
231
256
  }
232
257
  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})),
258
+ ...(item.pending_options === undefined ? [] : [{ref: item.pending_options, answer: undefined, record: itemPath + '.pending_options'}]),
259
+ ...answers.map((answer, index) => ({answer, record: index === 0 ? itemPath + '.' + answerKey : `${itemPath}.history[${index - 1}]`}))
260
+ .filter(({answer}) => object(answer.choice).spec === 'rig-create/interview-choice@1')
261
+ .map(({answer, record}) => ({ref: object(answer.choice).set, answer, record})),
236
262
  ];
237
263
  for (const entry of entries) {
238
264
  const ref = binding(entry.ref);
239
265
  const prior = seen.get(ref.sha256);
240
266
  if (prior !== undefined) {
241
267
  if (prior !== ref.path) return invalid('A retained set hash has conflicting paths');
242
- continue;
243
268
  }
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
269
  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)))) {
270
+ let raw: RecordData;
271
+ let set: InterviewSet;
272
+ try {
273
+ raw = readSet(root, ref);
274
+ const expectedStage = allowed.length === 1 ? allowed[0]! :
275
+ ['rig_type','reference','seethrough','assemble'].includes(String(item.id)) ? 'interview' : 'rigging-interview';
276
+ set = validateSet(raw, item.id, [expectedStage]);
277
+ } catch (error) {
278
+ if (editable) throw error;
279
+ const answer = entry.answer!;
280
+ historical.push({question: String(item.id), verbatim: typeof answer.verbatim === 'string' ? answer.verbatim : '',
281
+ by: typeof answer.by === 'string' ? answer.by : undefined, at: typeof answer.at === 'string' ? answer.at : undefined,
282
+ ref, record: entry.record, answer});
283
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: String(item.id), record: entry.record, ref,
284
+ ...(typeof answer.at === 'string' ? {at: answer.at} : {})});
285
+ continue;
286
+ }
287
+ if (editable && (set.stage === 'interview' || set.stage === 'rigging-interview') &&
288
+ (object(interview.order).spec !== 'rig-create/stage-order@2' || !Number.isFinite(date(object(interview.order).choices_adopted_at)))) {
250
289
  throw new Error('INTERVIEW_CHOICE_REQUIRED: Adopt create choices before selecting');
251
290
  }
252
291
  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);
292
+ const sceneKind = object(raw.context).kind === 'scene';
293
+ if (!editable && sceneKind) sceneAnswers++;
294
+ const evaluate = (at: number, record: string) => {
295
+ try {
296
+ const {legacy, ...context} = inspectContext(root, project, raw, set, at, editable);
297
+ if (legacy) diagnostics.push({code: 'INTERVIEW_OPTIONS_SCENE_LEGACY', question: set.question, record, ref, at: new Date(at).toISOString()});
298
+ return context;
299
+ } catch (error) {
300
+ if (editable || !(error instanceof Error) || !error.message.startsWith('INTERVIEW_OPTIONS_STALE:')) throw error;
301
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: set.question, record, ref,
302
+ ...(Number.isFinite(at) ? {at: new Date(at).toISOString()} : {})});
303
+ return {images: [], hasParts: false};
304
+ }
305
+ };
306
+ const context = evaluate(editable ? now : date(entry.answer?.at), entry.record);
307
+ const decision = object(entry.answer?.agent_decision);
308
+ if (!editable && ['at', 'value', 'fragments'].some(key => Object.hasOwn(decision, key))) {
309
+ evaluate(date(decision.at), entry.record + '.agent_decision');
310
+ }
254
311
  questions.push({ref, set, editable, answer: entry.answer, ...context});
255
312
  seen.set(ref.sha256, ref.path);
256
313
  }
257
314
  }
258
315
  }
259
- return {root, hash: digest(bytes), project, questions, historical};
316
+ return {root, hash: digest(bytes), project, questions, historical, diagnostics, sceneAnswers};
260
317
  }
@@ -35,6 +35,7 @@ async function body(req: Request) {
35
35
  export const interviewRefusals = [
36
36
  'INTERVIEW_UNAVAILABLE', 'INTERVIEW_SOURCE_MISMATCH', 'INTERVIEW_CHOICE_INVALID',
37
37
  'INTERVIEW_CHOICE_CONSTRAINT', 'INTERVIEW_CHOICE_REQUIRED', 'INTERVIEW_OPTIONS_INVALID',
38
+ 'INTERVIEW_CONTEXT_KIND_UNSUPPORTED',
38
39
  'INTERVIEW_OPTIONS_FILE', 'INTERVIEW_OPTIONS_STALE', 'INTERVIEW_PICKS_OUTPUT',
39
40
  ] as const;
40
41
  export function interviewRequest(path: string) {
@@ -55,7 +56,9 @@ export function interviewRoutes(root: string, output: string, capability: string
55
56
  };
56
57
  const current = async () => {
57
58
  await joined?.assertCurrent();
58
- if (readProject(opened.root).hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
59
+ const validated = readProject(opened.root);
60
+ if (validated.hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
61
+ return validated;
59
62
  };
60
63
  return async (req: Request, origin: string): Promise<Response | undefined> => {
61
64
  const url = new URL(req.url);
@@ -65,18 +68,24 @@ export function interviewRoutes(root: string, output: string, capability: string
65
68
  try {
66
69
  if (joined && interviewRequest(url.pathname) && !joined.available) return json({error:'INTERVIEW_UNAVAILABLE'}, 404);
67
70
  if (req.method === 'GET' && url.pathname === '/api/interview') {
68
- await current();
71
+ const validated = await current();
69
72
  const dir = destination();
70
- return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:opened.historical, questions:opened.questions.map(question => ({
73
+ return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
71
74
  ...question, saved:question.editable ? readPicks(dir, question) : null,
72
75
  images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
73
76
  }))});
74
77
  }
75
78
  const image = /^\/api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(url.pathname);
76
79
  if (image && req.method === 'GET') {
77
- await current();
78
- const asset = opened.questions.find(question => question.ref.sha256 === image[1])?.images[Number(image[2])];
79
- if (!asset) return json({error:'Not found'}, 404);
80
+ const validated = await current();
81
+ const index = Number(image[2]);
82
+ const asset = validated.questions.find(question => question.ref.sha256 === image[1] && question.images[index])?.images[index];
83
+ if (!asset) {
84
+ if (validated.diagnostics.some(diagnostic => diagnostic.ref.sha256 === image[1] && diagnostic.code === 'INTERVIEW_OPTIONS_STALE')) {
85
+ throw new Error('INTERVIEW_OPTIONS_STALE: Image evidence changed');
86
+ }
87
+ return json({error:'Not found'}, 404);
88
+ }
80
89
  let bytes: Buffer;
81
90
  try {bytes = boundBytes(opened.root, asset.ref);}
82
91
  catch {throw new Error('INTERVIEW_OPTIONS_STALE: Image bytes changed');}
@@ -0,0 +1,109 @@
1
+ /** Private scene option gate, from Create PROJECT rule 4. */
2
+ import {createHash} from 'node:crypto';
3
+ import {isDeepStrictEqual as equal} from 'node:util';
4
+ import type {SetRef} from './interview-project.ts';
5
+
6
+ type Data = Record<string, unknown>;
7
+ const object = (value: unknown): Data => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
8
+ const records = (value: unknown): Data[] => Array.isArray(value) ? value.map(object) : [];
9
+ const date = (value: unknown) => typeof value === 'string' ? Date.parse(value) : NaN;
10
+ const text = (value: unknown): value is string => typeof value === 'string' && !!value.trim();
11
+ const hash = (value: unknown) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
12
+ const count = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0;
13
+ const path = (value: unknown): value is string => text(value) && !value.startsWith('/') && !/^[a-z]:/i.test(value) &&
14
+ !value.includes('\\') && value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
15
+ const human = (value: unknown) => text(value) && value.toLowerCase() !== 'agent';
16
+ const stages = ['interview', 'plan-approved', 'parts', 'parts-review', 'rigging-interview', 'rigging', 'rig-review', 'post-interview', 'post', 'direction-review', 'accepted'];
17
+ const stale = (): never => {throw new Error('INTERVIEW_OPTIONS_STALE: scene context');};
18
+
19
+ function closed(value: unknown, required: string[], optional: string[] = []): boolean {
20
+ const data = object(value);
21
+ return data === value && required.every(key => Object.hasOwn(data, key)) &&
22
+ Object.keys(data).every(key => required.includes(key) || optional.includes(key));
23
+ }
24
+ const binding = (value: unknown) => closed(value, ['path', 'sha256']) && path(object(value).path) && hash(object(value).sha256);
25
+ function box(value: unknown): boolean {
26
+ return closed(value, ['x', 'y', 'width', 'height']) && Object.values(object(value)).every(n => typeof n === 'number');
27
+ }
28
+ function citation(value: unknown): boolean {
29
+ if (!closed(value, [], ['guide', 'asks', 'quote', 'delegated'])) return false;
30
+ const data = object(value);
31
+ return (!('guide' in data) || typeof data.guide === 'string') &&
32
+ (!('quote' in data) || typeof data.quote === 'string') &&
33
+ (!('delegated' in data) || typeof data.delegated === 'boolean') &&
34
+ (!('asks' in data) || Array.isArray(data.asks) && data.asks.every(ask => typeof ask === 'string'));
35
+ }
36
+ function plate(value: unknown): boolean {
37
+ const p = object(value), registered = object(p.registered);
38
+ return closed(value, ['role', 'path', 'sha256', 'width', 'height', 'rect', 'registered'], ['citation']) &&
39
+ ['background', 'foreground'].includes(String(p.role)) && path(p.path) && hash(p.sha256) && count(p.width) && count(p.height) && box(p.rect) &&
40
+ closed(p.registered, ['kind', 'ref']) && ['input', 'derived'].includes(String(registered.kind)) && text(registered.ref) &&
41
+ (!('citation' in p) || citation(p.citation));
42
+ }
43
+ function document(value: Data, n: unknown): boolean {
44
+ const rig = object(value.rig), animation = object(rig.animation), acceptance = object(rig.acceptance);
45
+ const signoff = object(acceptance.signoff), reviewPackage = object(acceptance.review_package), frame = object(value.frame);
46
+ return closed(value, ['schema', 'n', 'rig', 'frame', 'plates', 'layers']) && value.schema === 'rig-create/scene@1' && count(value.n) && value.n === n &&
47
+ closed(value.rig, ['version', 'acceptance', 'model', 'animation']) && count(rig.version) && binding(rig.model) &&
48
+ closed(rig.animation, ['name'], ['frames']) && text(animation.name) && (!('frames' in animation) || binding(animation.frames)) &&
49
+ closed(rig.acceptance, ['signoff', 'verdict', 'review_package']) && typeof acceptance.verdict === 'string' && /^versions\[\d+\]\.verdicts\[\d+\]$/.test(acceptance.verdict) &&
50
+ closed(acceptance.review_package, ['path', 'sha256']) && text(reviewPackage.path) && hash(reviewPackage.sha256) &&
51
+ closed(acceptance.signoff, ['stage', 'checkpoint', 'at']) && signoff.stage === 'rig-review' && signoff.checkpoint === null && Number.isFinite(date(signoff.at)) &&
52
+ closed(value.frame, ['space', 'stage']) && frame.space === 'rig-world-y-up' && box(frame.stage) &&
53
+ Array.isArray(value.plates) && value.plates.every(plate) && Array.isArray(value.layers) && value.layers.every(layer => typeof layer === 'string');
54
+ }
55
+
56
+ export function coveringChange(project: Data, stage: string, after: number, through: number): boolean {
57
+ const changes = [...records(project.reopens), ...records(project.amendments).map((entry): Data => ({...entry, stage: object(entry.target).stage}))];
58
+ return changes.some(change => {
59
+ const index = stages.indexOf(String(change.stage)), at = date(change.at);
60
+ return index >= 0 && index <= stages.indexOf(stage) && at > after && at <= through;
61
+ });
62
+ }
63
+ function sorted(value: unknown): unknown {
64
+ if (Array.isArray(value)) return value.map(sorted);
65
+ const data = object(value);
66
+ if (data !== value) return value;
67
+ return Object.fromEntries(Object.keys(data).sort().map(key => [key, sorted(data[key])]));
68
+ }
69
+ function current(project: Data, scene: Data, at: number): boolean {
70
+ const live = records(project.versions).map((version, index) => ({version, index})).filter(({version}) =>
71
+ version.kind === 'rig' && date(version.at) <= at && !coveringChange(project, 'rig-review', date(version.at) - 1, at));
72
+ const latest = live.sort((a, b) => Number(b.version.n) - Number(a.version.n))[0];
73
+ if (!latest || latest.version.n !== object(scene.rig).version) return false;
74
+ const {version, index} = latest;
75
+ const verdicts = records(version.verdicts);
76
+ const operative = verdicts.map((verdict, index) => ({verdict, index})).filter(({verdict}) =>
77
+ verdict.review === 'rig-review' && human(verdict.by) && verdict.verdict !== 'provisional' && date(verdict.at) <= at).at(-1);
78
+ if (!operative || operative.verdict.verdict !== 'accepted') return false;
79
+ const signature = records(project.signoffs).filter(signoff => signoff.stage === 'rig-review' && signoff.checkpoint === null &&
80
+ human(signoff.by) && date(signoff.at) <= at && object(signoff.target).version === version.n &&
81
+ !coveringChange(project, 'rig-review', date(signoff.at) - 1, at)).reverse().sort((a, b) => date(b.at) - date(a.at))[0];
82
+ if (!signature) return false;
83
+ const target = object(signature.target), pkg = object(version.review_package);
84
+ const packageHash = createHash('sha256').update(JSON.stringify(sorted({config: pkg.config, files: pkg.files}))).digest('hex');
85
+ if (target.verdict !== `versions[${index}].verdicts[${operative.index}]` ||
86
+ !equal(target.review_package, {path: `versions[${index}].review_package`, sha256: packageHash})) return false;
87
+ return equal(object(scene.rig).acceptance, {
88
+ signoff: {stage: signature.stage, checkpoint: signature.checkpoint, at: signature.at},
89
+ verdict: target.verdict, review_package: target.review_package,
90
+ });
91
+ }
92
+
93
+ export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data) {
94
+ if (project.scenes === undefined) return undefined;
95
+ if (!Array.isArray(project.scenes)) return stale();
96
+ const entries = records(project.scenes);
97
+ for (const [index, entry] of entries.entries()) {
98
+ if (!closed(entry, ['n', 'path', 'sha256', 'at', 'by']) || entry.n !== index + 1 ||
99
+ entry.path !== `evidence/scene/s${index + 1}.json` || !hash(entry.sha256) || !human(entry.by) ||
100
+ typeof entry.at !== 'string' || !entry.at.endsWith('Z') || !Number.isFinite(date(entry.at))) return stale();
101
+ }
102
+ const candidate = entries.filter(entry => date(entry.at) <= at).at(-1);
103
+ if (!candidate) return undefined;
104
+ const reference = {n: candidate.n, path: candidate.path as string, sha256: candidate.sha256 as string};
105
+ let scene: Data;
106
+ try {scene = read(reference);} catch {return stale();}
107
+ if (!document(scene, candidate.n)) return stale();
108
+ return {context: {kind: 'scene', scene: reference}, current: current(project, scene, at), document: scene};
109
+ }
package/src/job-source.ts CHANGED
@@ -323,7 +323,12 @@ export async function prepareJobSource(options: {
323
323
  if (jobHash(bytes) !== record.sha256) throw new JobError('JOB_RECORD_MOVED');
324
324
  try { JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
325
325
  catch { throw new JobError('JOB_RECORD_INCOMPLETE'); }
326
- if (record.path === 'project.json') project = readProject(root.path);
326
+ if (record.path === 'project.json') {
327
+ project = readProject(root.path);
328
+ // #555 owns API@2 diagnostic carriage. Refuse before publication lookup
329
+ // or snapshot writes when this reader's retained records need it.
330
+ if (project.sceneAnswers || project.diagnostics.length) throw new JobError('JOB_RECORD_INCOMPLETE');
331
+ }
327
332
  } else {
328
333
  try { lstatSync(join(root.path, 'project.json')); throw new JobError('JOB_FREEZE_REQUIRED'); }
329
334
  catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
package/web/catalog-en.ts CHANGED
@@ -45,6 +45,9 @@ export const enCatalog: Readonly<Record<string, string>> = {
45
45
  "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
46
46
  "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.",
47
47
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: Project or source changed. Reopen the inspection.",
48
+ "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: This option context kind is unsupported.",
49
+ "INTERVIEW_OPTIONS_SCENE_LEGACY": "INTERVIEW_OPTIONS_SCENE_LEGACY: This earlier scene context remains readable. Redraft against the current context before new work.",
50
+ "interview.historicalIssue": "INTERVIEW_OPTIONS_STALE: The context of this historical record could not be validated.",
48
51
  "interview.joinedDraft": "Draft {0} · project {1} · source {2}",
49
52
  "interview.joined": "Create version {0} · project SHA-256 {1} · inspection SHA-256 {2}",
50
53
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: The inspection does not match the designated Create package.",
package/web/catalog-ko.ts CHANGED
@@ -45,6 +45,9 @@ export const koCatalog: Readonly<Record<string, string>> = {
45
45
  "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
46
46
  "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: 대기 중인 파츠 검토와 명시적으로 지정한 판정 출력 디렉터리가 필요합니다.",
47
47
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: 프로젝트 또는 원본이 바뀌었어요. 검토를 다시 여세요.",
48
+ "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: 지원하지 않는 선택지 문맥 유형입니다.",
49
+ "INTERVIEW_OPTIONS_SCENE_LEGACY": "INTERVIEW_OPTIONS_SCENE_LEGACY: 이전 규칙의 장면 문맥을 읽었습니다. 새 작업 전에 현재 문맥으로 선택지를 다시 준비하세요.",
50
+ "interview.historicalIssue": "INTERVIEW_OPTIONS_STALE: 이 과거 기록의 문맥을 검증할 수 없습니다.",
48
51
  "interview.joinedDraft": "초안 {0} · 프로젝트 {1} · 원본 {2}",
49
52
  "interview.joined": "Create 버전 {0} · 프로젝트 SHA-256 {1} · 검토 SHA-256 {2}",
50
53
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: 검토 대상이 지정한 Create 패키지와 일치하지 않아요.",
@@ -1,4 +1,4 @@
1
- import type { HistoricalInterview, InterviewQuestion } from '../src/interview-project.ts';
1
+ import type { HistoricalInterview, InterviewQuestion, InterviewDiagnostic } from '../src/interview-project.ts';
2
2
  import type { Picks } from '../src/interview-picks.ts';
3
3
  import { onLanguageChange, t } from './i18n.ts';
4
4
  import type { InstanceAccess } from './instance-access.ts';
@@ -10,6 +10,7 @@ export const interviewErrors: Readonly<Record<string,string>> = {
10
10
  INTERVIEW_CHOICE_INVALID:'interview.invalid',
11
11
  INTERVIEW_CHOICE_CONSTRAINT:'interview.constraint',
12
12
  INTERVIEW_CHOICE_REQUIRED:'interview.required',
13
+ INTERVIEW_CONTEXT_KIND_UNSUPPORTED:'INTERVIEW_CONTEXT_KIND_UNSUPPORTED',
13
14
  INTERVIEW_OPTIONS_INVALID:'interview.invalidOptions',
14
15
  INTERVIEW_OPTIONS_FILE:'interview.file',
15
16
  INTERVIEW_OPTIONS_STALE:'interview.stale',
@@ -33,11 +34,11 @@ async function request(access: InstanceAccess, path: string, body?: Picks) {
33
34
  }
34
35
 
35
36
  export async function mountInterview(host: HTMLElement, access: InstanceAccess) {
36
- let data: {questions:Question[];historical:HistoricalInterview[]; binding?:{projectHash:string;sourceHash:string;version?:number;draftId?:string}};
37
+ let data: {questions:Question[];historical:HistoricalInterview[]; diagnostics?:InterviewDiagnostic[]; binding?:{projectHash:string;sourceHash:string;version?:number;draftId?:string}};
37
38
  try {data = await request(access, '/api/interview');}
38
39
  catch (error) {
39
40
  const render = () => {host.textContent = t(errorKey(error));};
40
- onLanguageChange(render); render(); return;
41
+ const unmount = onLanguageChange(render); render(); return unmount;
41
42
  }
42
43
  const {questions, historical:legacy} = data;
43
44
  const drafts = questions.map(question => {
@@ -55,17 +56,28 @@ export async function mountInterview(host: HTMLElement, access: InstanceAccess)
55
56
  const joined = data.binding;
56
57
  const source = joined ? element('p', t(joined.draftId===undefined?'interview.joined':'interview.joinedDraft', [joined.draftId??String(joined.version), joined.projectHash, joined.sourceHash])) : null;
57
58
  if (source) source.className = 'interview-binding';
59
+ const diagnostics = element('section');
60
+ diagnostics.className = 'interview-diagnostics';
61
+ diagnostics.setAttribute('role', 'status');
62
+ for (const diagnostic of data.diagnostics ?? []) {
63
+ const message = diagnostic.code === 'INTERVIEW_OPTIONS_STALE' ? 'interview.historicalIssue' : diagnostic.code;
64
+ diagnostics.append(element('p', t(message)),
65
+ element('code', [diagnostic.question, diagnostic.record, diagnostic.at, diagnostic.ref.path, diagnostic.ref.sha256].filter(Boolean).join(' · ')));
66
+ }
58
67
  const archive = element('details');
59
68
  archive.append(element('summary', t('interview.legacy')));
60
69
  for (const answer of legacy) {
61
70
  const item = element('section');
62
71
  item.append(element('h3', answer.question), element('p', [answer.by,answer.at].filter(Boolean).join(' · ')),
63
72
  element('pre', answer.verbatim));
73
+ if (answer.ref) item.append(element('code', answer.ref.path + ' · ' + answer.ref.sha256));
74
+ if (answer.answer) item.append(element('pre', [answer.answer.by, answer.answer.at, answer.answer.source].filter(value => typeof value === 'string').join(' · ')));
64
75
  archive.append(item);
65
76
  }
66
77
  if (!questions.length) {
67
78
  host.replaceChildren(element('p', t('interview.empty')));
68
79
  if (source) host.prepend(source);
80
+ host.append(diagnostics);
69
81
  if (legacy.length) {archive.open = true; host.append(archive);}
70
82
  return;
71
83
  }
@@ -109,6 +121,10 @@ export async function mountInterview(host: HTMLElement, access: InstanceAccess)
109
121
  const provenance = element('p', t('interview.provenance', [question.set.drafted_by, question.set.drafted_at]));
110
122
  const binding = element('code', question.ref.path + ' · ' + question.ref.sha256);
111
123
  form.append(provenance, binding);
124
+ if (question.answer) {
125
+ form.append(element('pre', [question.answer.by, question.answer.at, question.answer.source].filter(value => typeof value === 'string').join(' · ')),
126
+ element('pre', typeof question.answer.verbatim === 'string' ? question.answer.verbatim : ''));
127
+ }
112
128
  const historical = question.answer?.choice as {picks?:Picks['picks'];note?:string} | undefined;
113
129
  const status = element('p'); status.setAttribute('role','status');
114
130
  const markUnsaved = () => {
@@ -181,7 +197,8 @@ export async function mountInterview(host: HTMLElement, access: InstanceAccess)
181
197
  };
182
198
  grid.append(art, form); host.replaceChildren(picker, grid);
183
199
  if (source) host.prepend(source);
200
+ host.append(diagnostics);
184
201
  if (legacy.length) host.append(archive);
185
202
  };
186
- onLanguageChange(render); render();
203
+ const unmount = onLanguageChange(render); render(); return unmount;
187
204
  }