rig-review 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/PARTS_VIEW.md +82 -3
- package/docs/REVIEW_PACKAGE.md +50 -12
- package/docs/STABILITY.md +232 -15
- package/docs/WORKFLOWS.md +37 -1
- package/package.json +1 -1
- package/src/cli.ts +52 -7
- package/src/job-act.ts +316 -8
- package/src/job-api.ts +821 -8
- package/src/job-cli.ts +219 -52
- package/src/job-contract.ts +299 -0
- package/src/job-front.ts +763 -23
- package/src/job-host.ts +9 -1
- package/src/job-hub.ts +11 -6
- package/src/job-session.ts +68 -9
- package/src/job-source.ts +787 -7
- package/src/job-store.ts +114 -8
- package/src/job-worker.ts +5 -1
- package/src/parts-server.ts +46 -7
- package/src/parts-view.ts +76 -14
- package/web/catalog-en.ts +9 -0
- package/web/catalog-ko.ts +9 -0
- package/web/job-rig-capture.ts +53 -11
- package/web/job-session.ts +196 -7
package/src/job-store.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Database } from 'bun:sqlite';
|
|
1
|
+
import { Database, constants as sqliteConstants } from 'bun:sqlite';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { chmodSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
@@ -106,6 +106,10 @@ function privateEntry(path: string, directory: boolean): void {
|
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
export interface JobStoreOpenOptions {
|
|
110
|
+
readonly readonly?: boolean;
|
|
111
|
+
}
|
|
112
|
+
|
|
109
113
|
/** One SQLite transaction seals the entire job, including its events, acts and
|
|
110
114
|
* idempotency receipts. IMMEDIATE transactions serialize independent daemons.
|
|
111
115
|
* FULL synchronous durability and the rollback journal survive process death.
|
|
@@ -113,10 +117,56 @@ function privateEntry(path: string, directory: boolean): void {
|
|
|
113
117
|
*/
|
|
114
118
|
export class JobStore<Data> {
|
|
115
119
|
readonly root: string;
|
|
116
|
-
private
|
|
120
|
+
private readOnly: boolean;
|
|
121
|
+
get isReadonly(): boolean { return this.readOnly; }
|
|
122
|
+
private db: Database;
|
|
123
|
+
private identities!: {directory: {dev: number; ino: number}; file: {dev: number; ino: number}};
|
|
124
|
+
private writeAdoption?: () => void;
|
|
117
125
|
|
|
118
|
-
|
|
126
|
+
|
|
127
|
+
constructor(directory: string, options: JobStoreOpenOptions = {}) {
|
|
128
|
+
this.readOnly = options.readonly === true;
|
|
119
129
|
try {
|
|
130
|
+
if (this.isReadonly) {
|
|
131
|
+
privateEntry(directory, true);
|
|
132
|
+
const directInfo = lstatSync(directory);
|
|
133
|
+
this.root = realpathSync(directory);
|
|
134
|
+
const realInfo = lstatSync(this.root);
|
|
135
|
+
if (directInfo.dev !== realInfo.dev || directInfo.ino !== realInfo.ino) {
|
|
136
|
+
throw new JobError('JOB_STORAGE_FAILED', 'State directory must not be a symlink');
|
|
137
|
+
}
|
|
138
|
+
const file = join(this.root, 'jobs.sqlite');
|
|
139
|
+
privateEntry(file, false);
|
|
140
|
+
for (const suffix of ['-journal', '-wal', '-shm']) {
|
|
141
|
+
let exists = false;
|
|
142
|
+
try { lstatSync(file + suffix); exists = true; }
|
|
143
|
+
catch (error) {
|
|
144
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
145
|
+
}
|
|
146
|
+
if (exists) throw new JobError('JOB_STORAGE_FAILED', 'Unrecovered SQLite sidecar present');
|
|
147
|
+
}
|
|
148
|
+
const fileInfo = lstatSync(file);
|
|
149
|
+
this.identities = {directory: {dev: directInfo.dev, ino: directInfo.ino}, file: {dev: fileInfo.dev, ino: fileInfo.ino}};
|
|
150
|
+
this.db = new Database(file, sqliteConstants.SQLITE_OPEN_READONLY | sqliteConstants.SQLITE_OPEN_NOFOLLOW);
|
|
151
|
+
try {
|
|
152
|
+
this.db.exec('PRAGMA query_only=ON; PRAGMA busy_timeout=1000;');
|
|
153
|
+
this.assertStorage();
|
|
154
|
+
const tables = new Set(
|
|
155
|
+
this.db.query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
|
|
156
|
+
.all().map(row => row.name),
|
|
157
|
+
);
|
|
158
|
+
for (const required of [
|
|
159
|
+
'jobs', 'job_closures', 'job_snapshot_owners',
|
|
160
|
+
'job_snapshot_reads', 'job_snapshot_tombstones', 'job_act_stills',
|
|
161
|
+
]) {
|
|
162
|
+
if (!tables.has(required)) throw new JobError('JOB_STORAGE_FAILED', 'Required job table missing');
|
|
163
|
+
}
|
|
164
|
+
} catch (error) {
|
|
165
|
+
this.db.close();
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
120
170
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
121
171
|
privateEntry(directory, true);
|
|
122
172
|
this.root = realpathSync(directory);
|
|
@@ -159,13 +209,55 @@ export class JobStore<Data> {
|
|
|
159
209
|
sha256 TEXT NOT NULL, binding TEXT NOT NULL, png BLOB NOT NULL, act_bytes BLOB NOT NULL,
|
|
160
210
|
PRIMARY KEY(job_id, act_id), UNIQUE(job_id, page_id, submission_id)
|
|
161
211
|
);`);
|
|
212
|
+
this.captureStorage();
|
|
162
213
|
} catch {
|
|
163
214
|
throw new JobError('JOB_STORAGE_FAILED', 'Private job storage could not be opened');
|
|
164
215
|
}
|
|
165
216
|
}
|
|
166
217
|
|
|
218
|
+
private captureStorage(): void {
|
|
219
|
+
const directory = lstatSync(this.root), file = lstatSync(join(this.root, 'jobs.sqlite'));
|
|
220
|
+
this.identities = {directory: {dev: directory.dev, ino: directory.ino}, file: {dev: file.dev, ino: file.ino}};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
assertStorage(): void {
|
|
224
|
+
for (const [path, captured, directory] of [
|
|
225
|
+
[this.root, this.identities.directory, true],
|
|
226
|
+
[join(this.root, 'jobs.sqlite'), this.identities.file, false],
|
|
227
|
+
] as const) {
|
|
228
|
+
privateEntry(path, directory);
|
|
229
|
+
const current = lstatSync(path);
|
|
230
|
+
if (current.dev !== captured.dev || current.ino !== captured.ino) throw new JobError('JOB_STORAGE_FAILED');
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Install the exact-job guard without opening a writable connection. */
|
|
235
|
+
allowExistingWrites(verify: () => void): void { this.writeAdoption = verify; }
|
|
236
|
+
|
|
237
|
+
/** Deferred snapshot: acceptance performs SELECTs only, ordered against sealClose. */
|
|
238
|
+
inspect<Value>(operation: () => Value): Value {
|
|
239
|
+
return this.db.transaction(operation).deferred();
|
|
240
|
+
}
|
|
241
|
+
|
|
167
242
|
private transaction<Value>(operation: () => Value): Value {
|
|
168
|
-
try {
|
|
243
|
+
try {
|
|
244
|
+
if (this.readOnly) {
|
|
245
|
+
if (!this.writeAdoption) throw new JobError('JOB_STORAGE_FAILED');
|
|
246
|
+
this.assertStorage();
|
|
247
|
+
const writable = new Database(join(this.root, 'jobs.sqlite'), sqliteConstants.SQLITE_OPEN_READWRITE | sqliteConstants.SQLITE_OPEN_NOFOLLOW);
|
|
248
|
+
try {
|
|
249
|
+
this.assertStorage();
|
|
250
|
+
writable.exec('PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000;');
|
|
251
|
+
} catch (error) { writable.close(); throw error; }
|
|
252
|
+
this.db.close(); this.db = writable; this.readOnly = false;
|
|
253
|
+
}
|
|
254
|
+
return this.db.transaction(() => {
|
|
255
|
+
if (this.writeAdoption) {
|
|
256
|
+
this.assertStorage(); this.writeAdoption(); this.writeAdoption = undefined;
|
|
257
|
+
}
|
|
258
|
+
return operation();
|
|
259
|
+
}).immediate();
|
|
260
|
+
}
|
|
169
261
|
catch (error) {
|
|
170
262
|
if (typeof (error as { code?: unknown }).code === 'string' &&
|
|
171
263
|
String((error as { code: string }).code).startsWith('SQLITE_')) {
|
|
@@ -176,10 +268,24 @@ export class JobStore<Data> {
|
|
|
176
268
|
}
|
|
177
269
|
|
|
178
270
|
get(jobId: string): StoredJob<Data> {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
271
|
+
try {
|
|
272
|
+
const row = this.db.query<JobRow, [string]>(`SELECT jobs.*, job_closures.document AS closure
|
|
273
|
+
FROM jobs LEFT JOIN job_closures USING(job_id) WHERE job_id=?`).get(jobId);
|
|
274
|
+
if (!row) throw new JobError('JOB_UNKNOWN');
|
|
275
|
+
return decode<Data>(row);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (error instanceof JobError) throw error;
|
|
278
|
+
throw new JobError('JOB_STORAGE_FAILED', 'Stored job state is invalid');
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
activeByRootKey(rootKey: string): StoredJob<Data> | null {
|
|
283
|
+
try {
|
|
284
|
+
const row = this.db.query<JobRow, [string]>('SELECT * FROM jobs WHERE root_key=? AND active=1').get(rootKey);
|
|
285
|
+
return row ? decode<Data>(row) : null;
|
|
286
|
+
} catch {
|
|
287
|
+
throw new JobError('JOB_STORAGE_FAILED', 'Stored job state is invalid');
|
|
288
|
+
}
|
|
183
289
|
}
|
|
184
290
|
|
|
185
291
|
open(rootKey: string, initialize: (jobId: string) => Data, canonicalRoot?: string): StoredJob<Data> {
|
package/src/job-worker.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
1
2
|
import { createJobHostPorts } from './job-api.ts';
|
|
2
3
|
import { JobSession, type JobSessionOptions } from './job-session.ts';
|
|
3
4
|
import type { JobHostPorts } from './job-contract.ts';
|
|
@@ -7,6 +8,7 @@ export interface JobWorkerOptions extends JobSessionOptions {
|
|
|
7
8
|
readonly port?: number;
|
|
8
9
|
/** Trusted Create #184 adapter installs its private writer-owned sibling.
|
|
9
10
|
* No project record key or binding-file format is defined by this callback.
|
|
11
|
+
* Reusable owner-host attachment (`reuseOnly`) belongs to JobHostOptions.
|
|
10
12
|
*/
|
|
11
13
|
readonly installWriterBinding?: (binding: {
|
|
12
14
|
readonly jobId: string;
|
|
@@ -23,9 +25,11 @@ export async function startJobWorker(options: JobWorkerOptions): Promise<{
|
|
|
23
25
|
readonly session: JobSession;
|
|
24
26
|
readonly ports: JobHostPorts;
|
|
25
27
|
readonly origin: string;
|
|
28
|
+
readonly listenerIncarnation: string;
|
|
26
29
|
stop(): void;
|
|
27
30
|
}> {
|
|
28
31
|
const session = new JobSession(options);
|
|
32
|
+
const listenerIncarnation = randomUUID();
|
|
29
33
|
let ports: JobHostPorts;
|
|
30
34
|
let stopped = false;
|
|
31
35
|
const server = Bun.serve({
|
|
@@ -48,7 +52,7 @@ export async function startJobWorker(options: JobWorkerOptions): Promise<{
|
|
|
48
52
|
};
|
|
49
53
|
try {
|
|
50
54
|
await options.installWriterBinding?.({ ...session.writerGrant(), origin });
|
|
51
|
-
return { session, ports, origin, stop };
|
|
55
|
+
return { session, ports, origin, listenerIncarnation, stop };
|
|
52
56
|
} catch {
|
|
53
57
|
stop();
|
|
54
58
|
throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');
|
package/src/parts-server.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { accessGate } from './open-protocol.ts';
|
|
|
6
6
|
import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
|
|
7
7
|
import {preparePartsComment} from './parts-comment-crops.ts';
|
|
8
8
|
import {serveReference} from './reference.ts';
|
|
9
|
-
import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict,
|
|
9
|
+
import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdictWithReceipt, servedImage, type PartsViewPackage, type PartsSaveReceipt } from './parts-view.ts';
|
|
10
10
|
|
|
11
11
|
const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
|
|
12
12
|
const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
|
|
@@ -36,13 +36,47 @@ async function bodyJson(req: Request): Promise<unknown> {
|
|
|
36
36
|
return JSON.parse(new TextDecoder().decode(body));
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
export interface
|
|
39
|
+
export interface PartsSavedEvent extends PartsSaveReceipt { saveCount: number }
|
|
40
|
+
export interface PartsServerOptions {
|
|
41
|
+
port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number;
|
|
42
|
+
onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void;
|
|
43
|
+
by?: string;
|
|
44
|
+
onSaved?: (event: PartsSavedEvent) => Promise<void>;
|
|
45
|
+
onNotifyFailure?: (error: Error) => void;
|
|
46
|
+
onWriteFailure?: (error: Error) => void;
|
|
47
|
+
}
|
|
40
48
|
|
|
41
49
|
export async function startPartsServer(pkg: PartsViewPackage, options: PartsServerOptions = {}) {
|
|
50
|
+
const by = options.by;
|
|
51
|
+
if (by !== undefined && (typeof by !== 'string' || !by.trim())) throw new Error('PARTS_VERDICT_INVALID: reviewer name must be nonblank');
|
|
42
52
|
const bundle = await buildWeb('parts');
|
|
43
53
|
let rawStop: ((closeActiveConnections?: boolean) => void) | null = null;
|
|
44
|
-
let
|
|
45
|
-
|
|
54
|
+
let pendingSaves = 0, saveCount = 0;
|
|
55
|
+
let saveQueue: Promise<void> = Promise.resolve();
|
|
56
|
+
let closing = false;
|
|
57
|
+
let notifyFailure: Error | null = null;
|
|
58
|
+
const live = createLiveLifecycle({ label: 'review parts', graceMs: options.graceMs, unopenedTimeoutMs: options.unopenedTimeoutMs, exitOnClose: options.exitOnClose, onClose: options.onClose, log: options.log, busy: () => pendingSaves > 0, stopServer: () => { rawStop?.(true); } });
|
|
59
|
+
const save = (req: Request) => {
|
|
60
|
+
if (closing) throw new Error('PARTS_VERDICT_WRITE_FAILED: server is closing');
|
|
61
|
+
pendingSaves++;
|
|
62
|
+
const result = saveQueue.then(async () => {
|
|
63
|
+
if (notifyFailure) throw notifyFailure;
|
|
64
|
+
if (saveCount === Number.MAX_SAFE_INTEGER) throw new Error('PARTS_VERDICT_WRITE_FAILED: save count exhausted');
|
|
65
|
+
const {verdict, receipt} = await saveVerdictWithReceipt(pkg, await bodyJson(req), undefined, by);
|
|
66
|
+
const event = {...receipt, saveCount: ++saveCount};
|
|
67
|
+
try { await options.onSaved?.(event); }
|
|
68
|
+
catch (error) {
|
|
69
|
+
notifyFailure = new Error('PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed', {cause: error});
|
|
70
|
+
options.onNotifyFailure?.(notifyFailure);
|
|
71
|
+
throw notifyFailure;
|
|
72
|
+
}
|
|
73
|
+
return verdict;
|
|
74
|
+
});
|
|
75
|
+
saveQueue = result.then(() => {}, error => {
|
|
76
|
+
if (error instanceof Error && error.message.startsWith('PARTS_VERDICT_WRITE_FAILED:')) options.onWriteFailure?.(error);
|
|
77
|
+
}).finally(() => { pendingSaves--; });
|
|
78
|
+
return result;
|
|
79
|
+
};
|
|
46
80
|
const handle = async (req: Request, port: number | undefined, srv: UpgradableServer): Promise<Response | undefined> => {
|
|
47
81
|
try {
|
|
48
82
|
const url = new URL(req.url), origin = `http://127.0.0.1:${port}`;
|
|
@@ -60,8 +94,7 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
|
|
|
60
94
|
if(url.pathname==='/api/parts/export'&&req.method==='GET'){await assertPartsUnchanged(pkg);const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
|
|
61
95
|
if (url.pathname === '/api/parts/verdict' && req.method === 'POST') {
|
|
62
96
|
if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
|
|
63
|
-
|
|
64
|
-
try { return json({ verdict: await saveVerdict(pkg, await bodyJson(req)) }); } finally { saving = false; }
|
|
97
|
+
return json({ verdict: await save(req) });
|
|
65
98
|
}
|
|
66
99
|
if(url.pathname==='/api/parts/painting'&&req.method==='GET'){if(!pkg.painting)return json({error:'PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting'},404);return serveReference(req,pkg.painting.abs,pkg.painting.sha256,headers);}
|
|
67
100
|
const difference=/^\/api\/parts\/difference\/(\d+)$/.exec(url.pathname);
|
|
@@ -92,5 +125,11 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
|
|
|
92
125
|
const server = Bun.serve({ hostname: '127.0.0.1', port: options.port ?? 4317, websocket: live.websocket, async fetch(req, srv) { const res = await handle(req, srv.port, srv); return res as Response; } });
|
|
93
126
|
rawStop = server.stop.bind(server);
|
|
94
127
|
server.stop = ((closeActiveConnections?: boolean) => { live.stop(); return rawStop!(closeActiveConnections); }) as typeof server.stop;
|
|
95
|
-
|
|
128
|
+
const shutdown = async () => {
|
|
129
|
+
closing = true;
|
|
130
|
+
await saveQueue;
|
|
131
|
+
live.stop();
|
|
132
|
+
await server.stop(false);
|
|
133
|
+
};
|
|
134
|
+
return Object.assign(server, { live, shutdown });
|
|
96
135
|
}
|
package/src/parts-view.ts
CHANGED
|
@@ -21,13 +21,14 @@ import {preparePartsComment,validateStoredPartsComment} from './parts-comment-cr
|
|
|
21
21
|
import {resolvedCropPath} from './comment-crops.ts';
|
|
22
22
|
import { createHash } from 'node:crypto';
|
|
23
23
|
import { existsSync } from 'node:fs';
|
|
24
|
-
import { mkdir, readFile, realpath, rename, rm, stat
|
|
24
|
+
import { mkdir, open, readFile, realpath, rename, rm, stat } from 'node:fs/promises';
|
|
25
25
|
import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
|
|
26
26
|
import { PNG } from 'pngjs';
|
|
27
27
|
import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
|
|
28
28
|
import { destinationDirectory } from './destination-directory.ts';
|
|
29
29
|
|
|
30
30
|
export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/2';
|
|
31
|
+
const NAMED_VERDICT_SCHEMA = 'rig-review-parts-verdict/3';
|
|
31
32
|
export const PARTS_VERDICT_FILE = 'parts-review.json';
|
|
32
33
|
export const PARTS_NOTE_LIMIT = 10000;
|
|
33
34
|
export type PartsViewMode = 'parts' | 'atlas';
|
|
@@ -553,8 +554,20 @@ async function packageVersion(): Promise<string> {
|
|
|
553
554
|
return (JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version;
|
|
554
555
|
}
|
|
555
556
|
|
|
556
|
-
|
|
557
|
-
|
|
557
|
+
async function verdictWrite<T>(operation: string, action: () => Promise<T>): Promise<T> {
|
|
558
|
+
try { return await action(); }
|
|
559
|
+
catch (error) {
|
|
560
|
+
const code = (error as NodeJS.ErrnoException).code ?? 'IO';
|
|
561
|
+
throw new Error(`PARTS_VERDICT_WRITE_FAILED: ${operation} (${code})`, {cause: error});
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
export interface PartsSaveReceipt { verdictPath: string; sha256: string; status: VerdictStatus }
|
|
566
|
+
|
|
567
|
+
/** One durable buffer, shared by standalone and joined saves. Attribution is launch configuration only. */
|
|
568
|
+
export async function saveVerdictWithReceipt(pkg: PartsViewPackage, input: unknown,
|
|
569
|
+
assertCurrent?: () => Promise<void>, by?: string): Promise<{verdict: PartsVerdict; receipt: PartsSaveReceipt}> {
|
|
570
|
+
if (by !== undefined && (typeof by !== 'string' || !by.trim())) refuse('PARTS_VERDICT_INVALID', 'reviewer name must be nonblank');
|
|
558
571
|
await assertCurrent?.();
|
|
559
572
|
await assertVerdictDestination(pkg);
|
|
560
573
|
await assertPartsUnchanged(pkg);
|
|
@@ -562,14 +575,37 @@ export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertC
|
|
|
562
575
|
const verdict = buildVerdict(pkg, input, await packageVersion());
|
|
563
576
|
for(const comment of verdict.comments)await preparePartsComment(pkg,comment,true);
|
|
564
577
|
await assertPartsUnchanged(pkg);
|
|
565
|
-
|
|
578
|
+
const stored = by === undefined ? verdict : {...verdict, schema: NAMED_VERDICT_SCHEMA, by};
|
|
579
|
+
const bytes = Buffer.from(JSON.stringify(stored, null, 2) + '\n');
|
|
580
|
+
const parent = dirname(pkg.verdictPath);
|
|
581
|
+
const firstCreated = await verdictWrite('mkdir', () => mkdir(parent, { recursive: true }));
|
|
566
582
|
const tmp = `${pkg.verdictPath}.${crypto.randomUUID()}.tmp`;
|
|
567
583
|
try {
|
|
568
|
-
await
|
|
584
|
+
await verdictWrite('write/fsync', async () => {
|
|
585
|
+
const file = await open(tmp, 'wx');
|
|
586
|
+
try { await file.writeFile(bytes); await file.sync(); }
|
|
587
|
+
finally { await file.close(); }
|
|
588
|
+
});
|
|
569
589
|
await assertVerdictDestination(pkg);
|
|
570
590
|
await assertCurrent?.();
|
|
571
|
-
await
|
|
572
|
-
|
|
591
|
+
await assertPartsUnchanged(pkg);
|
|
592
|
+
await verdictWrite('rename', () => rename(tmp, pkg.verdictPath));
|
|
593
|
+
// Flush the file's entry and every newly created directory's entry in its parent.
|
|
594
|
+
const last = firstCreated ? dirname(firstCreated) : parent;
|
|
595
|
+
for (let directory = parent; ; directory = dirname(directory)) {
|
|
596
|
+
await verdictWrite('directory fsync', async () => {
|
|
597
|
+
const handle = await open(directory, 'r');
|
|
598
|
+
try { await handle.sync(); } finally { await handle.close(); }
|
|
599
|
+
});
|
|
600
|
+
if (directory === last) break;
|
|
601
|
+
}
|
|
602
|
+
} finally { await verdictWrite('temporary cleanup', () => rm(tmp, { force: true })); }
|
|
603
|
+
return {verdict, receipt: {verdictPath: pkg.verdictPath, sha256: createHash('sha256').update(bytes).digest('hex'), status: verdict.status}};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** Shared callers retain the ordinary normalized verdict and produce no save notification. */
|
|
607
|
+
export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertCurrent?: () => Promise<void>): Promise<PartsVerdict> {
|
|
608
|
+
const {verdict} = await saveVerdictWithReceipt(pkg, input, assertCurrent);
|
|
573
609
|
return verdict;
|
|
574
610
|
}
|
|
575
611
|
|
|
@@ -581,16 +617,42 @@ export type VerdictStale = 'files' | 'flags' | null;
|
|
|
581
617
|
* `source.sha256` alone; the page also requires `source.flags`, so a reviewer never sees a sign-off over flags they
|
|
582
618
|
* were not shown.
|
|
583
619
|
*/
|
|
584
|
-
|
|
620
|
+
async function readVerdictSnapshot(pkg: PartsViewPackage): Promise<{
|
|
621
|
+
verdict: PartsVerdict | null; stale: VerdictStale; by: string | null; savedFileSha256: string | null;
|
|
622
|
+
}> {
|
|
585
623
|
let raw: unknown;
|
|
586
|
-
|
|
587
|
-
|
|
624
|
+
const unavailable = {verdict: null, by: null, savedFileSha256: null};
|
|
625
|
+
let bytes: Buffer;
|
|
626
|
+
try { bytes = await readFile(pkg.verdictPath); }
|
|
627
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {...unavailable, stale: null}; throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read'); }
|
|
628
|
+
try{raw=JSON.parse(bytes.toString('utf8'));}catch{throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');}
|
|
588
629
|
const v = record(raw), source = record(v?.source), now = verdictSource(pkg);
|
|
589
|
-
if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1'].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
|
|
590
|
-
|
|
591
|
-
if (
|
|
630
|
+
if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1',NAMED_VERDICT_SCHEMA].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
|
|
631
|
+
let by: string | null = null;
|
|
632
|
+
if (v.schema === NAMED_VERDICT_SCHEMA) {
|
|
633
|
+
if (typeof v.by !== 'string' || !v.by.trim()) refuse('PARTS_VERDICT_INVALID', 'saved reviewer name must be nonblank');
|
|
634
|
+
by = v.by as string;
|
|
635
|
+
}
|
|
636
|
+
if(v.mode!==pkg.mode||source.sha256!==now.sha256)return {...unavailable,stale:'files'};
|
|
637
|
+
if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) return { ...unavailable, stale: 'flags' };
|
|
592
638
|
const date=new Date(String(v.updatedAt));if(!Number.isFinite(date.getTime()))throw new Error('PARTS_VERDICT_INVALID: saved verdict date is invalid');
|
|
593
|
-
const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);
|
|
639
|
+
const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);
|
|
640
|
+
for(const c of normalized.comments)await validateStoredPartsComment(pkg,c);
|
|
641
|
+
return {verdict:normalized,stale:null,by,savedFileSha256:createHash('sha256').update(bytes).digest('hex')};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Explicitly project the shared response so retrieval metadata cannot escape through joined wrappers. */
|
|
645
|
+
export async function readVerdict(pkg: PartsViewPackage): Promise<{verdict: PartsVerdict | null; stale: VerdictStale}> {
|
|
646
|
+
const {verdict, stale} = await readVerdictSnapshot(pkg);
|
|
647
|
+
return {verdict, stale};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Standalone CLI retrieval metadata and content come from one validated saved-file buffer. */
|
|
651
|
+
export async function readPartsVerdictJson(pkg: PartsViewPackage): Promise<string> {
|
|
652
|
+
const saved = await readVerdictSnapshot(pkg);
|
|
653
|
+
if (!saved.verdict) refuse('PARTS_VERDICT_UNAVAILABLE', 'save a verdict first');
|
|
654
|
+
await assertPartsUnchanged(pkg);
|
|
655
|
+
return JSON.stringify({...JSON.parse(exportPartsVerdict(saved.verdict!, 'json')), by: saved.by, savedFileSha256: saved.savedFileSha256}, null, 2) + '\n';
|
|
594
656
|
}
|
|
595
657
|
|
|
596
658
|
/** What the page reads: no absolute path leaves the server but the verdict file's name. */
|
package/web/catalog-en.ts
CHANGED
|
@@ -3286,6 +3286,15 @@ export const enCatalog: Readonly<Record<string, string>> = {
|
|
|
3286
3286
|
"PARTS_VERDICT_INVALID: saved verdict is not valid JSON": "PARTS_VERDICT_INVALID: saved verdict is not valid JSON",
|
|
3287
3287
|
"PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid": "PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid",
|
|
3288
3288
|
"PARTS_VERDICT_INVALID: saved verdict date is invalid": "PARTS_VERDICT_INVALID: saved verdict date is invalid",
|
|
3289
|
+
"PARTS_VERDICT_INVALID: reviewer name must be nonblank": "PARTS_VERDICT_INVALID: reviewer name must be nonblank",
|
|
3290
|
+
"PARTS_VERDICT_INVALID: saved reviewer name must be nonblank": "PARTS_VERDICT_INVALID: saved reviewer name must be nonblank",
|
|
3291
|
+
"PARTS_VERDICT_WRITE_FAILED: {0} ({1})": "PARTS_VERDICT_WRITE_FAILED: {0} ({1})",
|
|
3292
|
+
"PARTS_VERDICT_WRITE_FAILED: server is closing": "PARTS_VERDICT_WRITE_FAILED: server is closing",
|
|
3293
|
+
"PARTS_VERDICT_WRITE_FAILED: save count exhausted": "PARTS_VERDICT_WRITE_FAILED: save count exhausted",
|
|
3294
|
+
"PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed": "PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed",
|
|
3295
|
+
"PARTS_VERDICT_NOTIFY_FAILED: stdout failed": "PARTS_VERDICT_NOTIFY_FAILED: stdout failed",
|
|
3296
|
+
"--by: expected a nonblank reviewer name": "--by: expected a nonblank reviewer name",
|
|
3297
|
+
"--by: launch only; incompatible with export or correction options": "--by: launch only; incompatible with export or correction options",
|
|
3289
3298
|
"Painting comparison": "Painting comparison",
|
|
3290
3299
|
"Overlay": "Overlay",
|
|
3291
3300
|
"Part opacity": "Part opacity",
|
package/web/catalog-ko.ts
CHANGED
|
@@ -3286,6 +3286,15 @@ export const koCatalog: Readonly<Record<string, string>> = {
|
|
|
3286
3286
|
"PARTS_VERDICT_INVALID: saved verdict is not valid JSON": "PARTS_VERDICT_INVALID: 저장된 판정이 올바른 JSON이 아니에요",
|
|
3287
3287
|
"PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid": "PARTS_VERDICT_INVALID: 저장된 판정의 스키마나 원본 연결이 잘못됐어요",
|
|
3288
3288
|
"PARTS_VERDICT_INVALID: saved verdict date is invalid": "PARTS_VERDICT_INVALID: 저장된 판정의 날짜가 잘못됐어요",
|
|
3289
|
+
"PARTS_VERDICT_INVALID: reviewer name must be nonblank": "PARTS_VERDICT_INVALID: 검토자 이름은 공백이 아닌 문자열이어야 해요",
|
|
3290
|
+
"PARTS_VERDICT_INVALID: saved reviewer name must be nonblank": "PARTS_VERDICT_INVALID: 저장된 판정의 검토자 이름이 비어 있거나 잘못됐어요",
|
|
3291
|
+
"PARTS_VERDICT_WRITE_FAILED: {0} ({1})": "PARTS_VERDICT_WRITE_FAILED: 판정을 저장하지 못했어요 — {0} ({1})",
|
|
3292
|
+
"PARTS_VERDICT_WRITE_FAILED: server is closing": "PARTS_VERDICT_WRITE_FAILED: 서버가 종료 중이라 판정을 저장할 수 없어요",
|
|
3293
|
+
"PARTS_VERDICT_WRITE_FAILED: save count exhausted": "PARTS_VERDICT_WRITE_FAILED: 저장 횟수 한도에 도달해 판정을 저장할 수 없어요",
|
|
3294
|
+
"PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed": "PARTS_VERDICT_NOTIFY_FAILED: 판정은 저장됐지만 저장 완료 알림을 전달하지 못했어요",
|
|
3295
|
+
"PARTS_VERDICT_NOTIFY_FAILED: stdout failed": "PARTS_VERDICT_NOTIFY_FAILED: 표준 출력(stdout)으로 저장 알림을 기록하지 못했어요",
|
|
3296
|
+
"--by: expected a nonblank reviewer name": "--by: 공백이 아닌 검토자 이름이 필요해요",
|
|
3297
|
+
"--by: launch only; incompatible with export or correction options": "--by: 실행 전용 옵션이라 내보내기 또는 수정 인계 옵션과 함께 쓸 수 없어요",
|
|
3289
3298
|
"Painting comparison": "원화 비교",
|
|
3290
3299
|
"Overlay": "오버레이",
|
|
3291
3300
|
"Part opacity": "파츠 불투명도",
|
package/web/job-rig-capture.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type {JobRigPresentation} from './viewport-capture.ts';
|
|
|
4
4
|
|
|
5
5
|
type DrawSource = Pick<JobRigCapture['binding'], 'publicationId' | 'instanceKey' | 'sourceHash' | 'pageId'>;
|
|
6
6
|
export interface JobRigDrawState {
|
|
7
|
-
player: Pick<RigPlayer, 'generation' | 'current' | 'time' | 'slots'> & {readonly renderer: object};
|
|
7
|
+
player: Pick<RigPlayer, 'generation' | 'current' | 'time' | 'slots' | 'entry'> & {readonly renderer: object};
|
|
8
8
|
frameGeneration: number | undefined;
|
|
9
9
|
presentation: JobRigPresentation | undefined;
|
|
10
10
|
source: DrawSource;
|
|
@@ -21,6 +21,8 @@ export interface JobRigDraw {
|
|
|
21
21
|
readonly drawGeneration: number;
|
|
22
22
|
readonly animation: string | null;
|
|
23
23
|
readonly time: number;
|
|
24
|
+
readonly trackTime: number;
|
|
25
|
+
readonly loop: boolean;
|
|
24
26
|
readonly playing: boolean;
|
|
25
27
|
readonly source: DrawSource;
|
|
26
28
|
readonly layout: string;
|
|
@@ -55,20 +57,63 @@ export function jobRigPixelPlacement(pane: Pick<DOMRect, 'left' | 'top'>,
|
|
|
55
57
|
};
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
function readPlayerTiming(state: JobRigDrawState): {animation: string | null; time: number; trackTime: number; loop: boolean} {
|
|
61
|
+
if (!Number.isFinite(state.player.time) || state.player.time < 0 || typeof state.playing !== 'boolean' ||
|
|
62
|
+
typeof state.player.entry !== 'function') {
|
|
63
|
+
throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
64
|
+
}
|
|
65
|
+
const entry = state.player.entry(0);
|
|
66
|
+
if (state.player.current === null) {
|
|
67
|
+
if (state.playing || state.player.time !== 0 ||
|
|
68
|
+
(entry !== null && (entry.animation !== null || entry.trackTime !== 0 || entry.animationTime !== 0))) {
|
|
69
|
+
throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
70
|
+
}
|
|
71
|
+
return {animation: null, time: 0, trackTime: 0, loop: false};
|
|
72
|
+
}
|
|
73
|
+
if (typeof state.player.current !== 'string' || !state.player.current || !entry ||
|
|
74
|
+
typeof entry.animation !== 'string' || entry.animation !== state.player.current ||
|
|
75
|
+
typeof entry.loop !== 'boolean' || !Number.isFinite(entry.trackTime) || entry.trackTime < 0 ||
|
|
76
|
+
entry.trackTime !== state.player.time || !Number.isFinite(entry.duration) || entry.duration < 0 ||
|
|
77
|
+
!Number.isFinite(entry.animationTime) || entry.animationTime < 0 || entry.animationTime > entry.duration) {
|
|
78
|
+
throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
79
|
+
}
|
|
80
|
+
return {animation: entry.animation, time: entry.animationTime, trackTime: entry.trackTime, loop: entry.loop};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function matchesDrawState(draw: JobRigDraw, state: JobRigDrawState): boolean {
|
|
84
|
+
if (draw.presentation !== state.presentation || draw.player !== state.player || draw.renderer !== state.player.renderer ||
|
|
85
|
+
draw.playerGeneration !== state.player.generation || state.frameGeneration !== draw.playerGeneration ||
|
|
86
|
+
draw.animation !== state.player.current || draw.trackTime !== state.player.time ||
|
|
87
|
+
draw.playing !== state.playing || draw.layout !== state.layout || sourceKey(draw.source) !== sourceKey(state.source)) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
const entry = state.player.entry(0);
|
|
91
|
+
if (draw.animation === null) {
|
|
92
|
+
return !draw.playing && !state.playing && draw.time === 0 && draw.trackTime === 0 && draw.loop === false && state.player.time === 0 &&
|
|
93
|
+
(entry === null || (entry.animation === null && entry.trackTime === 0 && entry.animationTime === 0));
|
|
94
|
+
}
|
|
95
|
+
return entry !== null && entry.animation === draw.animation && entry.loop === draw.loop &&
|
|
96
|
+
entry.trackTime === draw.trackTime && entry.animationTime === draw.time &&
|
|
97
|
+
Number.isFinite(entry.duration) && entry.duration >= 0 && draw.time >= 0 && draw.time <= entry.duration;
|
|
98
|
+
}
|
|
99
|
+
|
|
58
100
|
/** Called after the public draw/present and viewport-render boundaries succeed. */
|
|
59
101
|
export function recordJobRigDraw(state: JobRigDrawState, drawGeneration: number): JobRigDraw {
|
|
60
102
|
if (!state.presentation || state.frameGeneration !== state.player.generation || !Number.isSafeInteger(drawGeneration) || drawGeneration < 1 ||
|
|
61
|
-
!Number.isSafeInteger(state.player.generation) || state.player.generation < 0
|
|
103
|
+
!Number.isSafeInteger(state.player.generation) || state.player.generation < 0) {
|
|
62
104
|
throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
63
105
|
}
|
|
106
|
+
const timing = readPlayerTiming(state);
|
|
64
107
|
return Object.freeze({
|
|
65
108
|
player: state.player,
|
|
66
109
|
renderer: state.player.renderer,
|
|
67
110
|
presentation: state.presentation,
|
|
68
111
|
playerGeneration: state.player.generation,
|
|
69
112
|
drawGeneration,
|
|
70
|
-
animation:
|
|
71
|
-
time:
|
|
113
|
+
animation: timing.animation,
|
|
114
|
+
time: timing.time,
|
|
115
|
+
trackTime: timing.trackTime,
|
|
116
|
+
loop: timing.loop,
|
|
72
117
|
playing: state.playing,
|
|
73
118
|
source: Object.freeze({...state.source}),
|
|
74
119
|
layout: state.layout,
|
|
@@ -80,16 +125,13 @@ export function freezeJobRigCapture(draw: JobRigDraw | undefined, state: JobRigD
|
|
|
80
125
|
copy: () => JobRigPixels): FrozenJobRigCapture {
|
|
81
126
|
if (!state.defaultCamera) throw new Error('JOB_STILL_CAMERA_NOT_FIXED');
|
|
82
127
|
if (!state.wholeRig || state.player.slots !== null) throw new Error('JOB_STILL_VIEW_UNSUPPORTED');
|
|
83
|
-
if (!draw) throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
84
|
-
if (draw.
|
|
85
|
-
|
|
86
|
-
draw.time !== state.player.time || draw.layout !== state.layout || sourceKey(draw.source) !== sourceKey(state.source)) {
|
|
128
|
+
if (!draw || typeof state.player.entry !== 'function') throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
129
|
+
if (draw.animation !== null && !draw.animation) throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
130
|
+
if (!matchesDrawState(draw, state)) {
|
|
87
131
|
throw new Error('JOB_STILL_BINDING_MISMATCH');
|
|
88
132
|
}
|
|
89
|
-
if (draw.animation !== null && !draw.animation) throw new Error('JOB_STILL_CAPTURE_FAILED');
|
|
90
133
|
const pixels = copy();
|
|
91
|
-
if (
|
|
92
|
-
state.player.time !== draw.time || draw.layout !== state.layout || sourceKey(draw.source) !== sourceKey(state.source)) {
|
|
134
|
+
if (!matchesDrawState(draw, state)) {
|
|
93
135
|
throw new Error('JOB_STILL_BINDING_MISMATCH');
|
|
94
136
|
}
|
|
95
137
|
if (!Number.isSafeInteger(pixels.width) || !Number.isSafeInteger(pixels.height) || pixels.width < 1 || pixels.height < 1 ||
|