rig-review 2.10.0 → 2.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/src/job-source.ts CHANGED
@@ -5,12 +5,12 @@ import { mkdir, open, rm, writeFile } from 'node:fs/promises';
5
5
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
6
6
  import { PNG } from 'pngjs';
7
7
  import {
8
- JOB_API_V3_SCHEMA,
8
+ JOB_API_V3_SCHEMA, JOB_PLAN_TEXT_FIELDS, JOB_PLAN_TEXT_SCHEMA,
9
9
  JOB_PARTS_ENUMERATOR_RANGE,
10
10
  } from './job-contract.ts';
11
11
  import type {
12
12
  JobCheckpointEvidence, JobFileIdentity, JobImageSetInput, JobInterviewDiagnostics, JobInterviewRecord, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
13
- JobSelector, JobSourceBinding, JobSubject,
13
+ JobSelector, JobSourceBinding, JobSubject, JobPlanTextProjection, JobPlanTextStep,
14
14
  OptionContext, OptionSource, PackageResultV3, PlanContext, PlanSource, ProjectRecord, PublishRequestV3,
15
15
  RecordFreeze, RecordOptionResult, RecordPlanResult, RecordPublicationReader, RecordPublishedContext,
16
16
  RecordReaderInput, RecordResult, RecordSource, RecordSubject,
@@ -234,6 +234,33 @@ function referenceRow(raw: unknown, row: number, hashed: boolean): JobPartsFileR
234
234
  return {path, role, ...(hashed ? {sha256: item.sha256 as string} : {})};
235
235
  }
236
236
 
237
+ function partsIdentityHeader(value: unknown): {raw: Record<string, unknown>; version: string} {
238
+ const raw = jobObject(value, ['enumeratorVersion', 'manifest', 'images']);
239
+ return {raw, version: jobPartsEnumeratorVersion(raw.enumeratorVersion)};
240
+ }
241
+
242
+ function partsManifest(value: unknown): JobFileIdentity {
243
+ try {
244
+ const raw = jobObject(value, ['path', 'sha256']);
245
+ const path = jobPath(raw.path);
246
+ if (posix.basename(path) !== 'parts.json') throw new Error('Manifest directory API');
247
+ return {path, sha256: jobSha(raw.sha256)};
248
+ } catch { throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_PATH_REFUSED manifest'); }
249
+ }
250
+
251
+ function partsReferenceList(value: unknown): unknown[] {
252
+ if (!Array.isArray(value) || value.length > maxSourceFiles) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
253
+ return value;
254
+ }
255
+
256
+ /** Pure declared identity decoder; official enumeration and native bytes remain preparation checks. */
257
+ export function parseJobPartsIdentity(value: unknown): JobPartsIdentity {
258
+ const {raw, version} = partsIdentityHeader(value);
259
+ const manifest = partsManifest(raw.manifest);
260
+ const images = partsReferenceList(raw.images).map((row, index) => referenceRow(row, index, true));
261
+ return {enumeratorVersion: version, manifest, images: images as JobPartsIdentity['images']};
262
+ }
263
+
237
264
  /** Membership, order and duplicate semantics belong solely to the trusted public
238
265
  * enumerator. Review compares its exact array and validates byte boundaries.
239
266
  */
@@ -242,22 +269,13 @@ async function prepareParts(root: string, snapshotRoot: string, claimed: JobPart
242
269
  const bytes = new Map<string, Buffer>();
243
270
  if (claimed === null) return {identity: null, bytes};
244
271
  if (!enumerator) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_ENUMERATOR_UNAVAILABLE');
245
- jobObject(claimed, ['enumeratorVersion', 'manifest', 'images']);
246
- const version = jobPartsEnumeratorVersion(claimed.enumeratorVersion);
272
+ const {version} = partsIdentityHeader(claimed);
247
273
  if (version !== jobPartsEnumeratorVersion(enumerator.version)) {
248
274
  throw new JobError('JOB_SOURCE_UNRETAINABLE',
249
275
  `PARTS_ENUMERATOR_VERSION_MISMATCH range="${JOB_PARTS_ENUMERATOR_RANGE}" received="${version}" installed="${enumerator.version}"`);
250
276
  }
251
- let manifestPath: string;
252
- try {
253
- jobObject(claimed.manifest, ['path', 'sha256']);
254
- manifestPath = jobPath(claimed.manifest.path);
255
- if (posix.basename(manifestPath) !== 'parts.json') throw new Error('Manifest directory API');
256
- jobSha(claimed.manifest.sha256);
257
- } catch { throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_PATH_REFUSED manifest'); }
258
- if (!Array.isArray(claimed.images) || claimed.images.length > maxSourceFiles) {
259
- throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
260
- }
277
+ const {path: manifestPath} = partsManifest(claimed.manifest);
278
+ const claimedImages = partsReferenceList(claimed.images);
261
279
  let manifestBytes: Buffer;
262
280
  try { manifestBytes = sourceBytes(root, manifestPath); }
263
281
  catch (error) {
@@ -282,11 +300,8 @@ async function prepareParts(root: string, snapshotRoot: string, claimed: JobPart
282
300
  throw new JobError('JOB_SOURCE_MISMATCH', 'PARTS_ENUMERATION_REFUSED' + rule);
283
301
  }
284
302
  } finally { await rm(enumerationRoot, {recursive: true, force: true}); }
285
- if (!Array.isArray(references) || references.length > maxSourceFiles) {
286
- throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
287
- }
288
- const official = references.map((raw, row) => referenceRow(raw, row, false));
289
- const supplied = claimed.images.map((raw, row) => referenceRow(raw, row, true));
303
+ const official = partsReferenceList(references).map((raw, row) => referenceRow(raw, row, false));
304
+ const supplied = claimedImages.map((raw, row) => referenceRow(raw, row, true));
290
305
  const difference = official.findIndex((row, i) => row.path !== supplied[i]?.path || row.role !== supplied[i]?.role);
291
306
  if (difference !== -1 || official.length !== supplied.length) {
292
307
  throw new JobError('JOB_SOURCE_MISMATCH',
@@ -655,7 +670,7 @@ async function readRecordPublishedPhase(
655
670
  return parseRecordPublishedContext(raw, input.result, input.record);
656
671
  }
657
672
 
658
- function readProjectRecordBytes(root: string, record: ProjectRecord): {
673
+ function readProjectRecordBytes(root: string, record: ProjectRecord, allowLegacySchema = false): {
659
674
  readonly bytes: Buffer;
660
675
  readonly project: Record<string, unknown>;
661
676
  } {
@@ -663,15 +678,15 @@ function readProjectRecordBytes(root: string, record: ProjectRecord): {
663
678
  try {
664
679
  stat = lstatSync(join(root, record.path));
665
680
  } catch {
666
- throw new JobError('JOB_RECORD_MOVED');
681
+ throw new JobError(allowLegacySchema ? 'JOB_SOURCE_UNRETAINABLE' : 'JOB_RECORD_MOVED');
667
682
  }
668
- if (!stat.isFile()) throw new JobError('JOB_RECORD_MOVED');
683
+ if (!stat.isFile()) throw new JobError(allowLegacySchema ? 'JOB_SOURCE_UNRETAINABLE' : 'JOB_RECORD_MOVED');
669
684
  if (stat.size > maxProjectBytes) throw new JobError('JOB_SOURCE_UNRETAINABLE');
670
685
  let bytes: Buffer;
671
686
  try {
672
687
  bytes = sourceBytes(root, record.path);
673
688
  } catch {
674
- throw new JobError('JOB_RECORD_MOVED');
689
+ throw new JobError(allowLegacySchema ? 'JOB_SOURCE_UNRETAINABLE' : 'JOB_RECORD_MOVED');
675
690
  }
676
691
  if (jobHash(bytes) !== record.sha256) throw new JobError('JOB_RECORD_MOVED');
677
692
  let project: Record<string, unknown>;
@@ -680,7 +695,7 @@ function readProjectRecordBytes(root: string, record: ProjectRecord): {
680
695
  } catch {
681
696
  throw new JobError('JOB_RECORD_INCOMPLETE');
682
697
  }
683
- if (project.schema !== 'rig-create/project@0') throw new JobError('JOB_RECORD_INCOMPLETE');
698
+ if (!allowLegacySchema && project.schema !== 'rig-create/project@0') throw new JobError('JOB_RECORD_INCOMPLETE');
684
699
  return { bytes, project };
685
700
  }
686
701
 
@@ -712,6 +727,83 @@ function readClosureFileBytes(root: string, file: JobFileIdentity): Buffer {
712
727
  return bytes;
713
728
  }
714
729
 
730
+ /** Delivery-only projection through the existing retained record reader. */
731
+ export function projectRetainedPlanText(retained: JobRetainedSourceV3): JobPlanTextProjection | undefined {
732
+ const {source, record} = retained;
733
+ const plan = source.plan;
734
+ if (!plan) return undefined;
735
+ let identity: {path: 'project.json'; sha256: string} | null = null;
736
+ const unavailable = (reason: Extract<JobPlanTextProjection, {status:'unavailable'}>['reason']): JobPlanTextProjection =>
737
+ ({schema:JOB_PLAN_TEXT_SCHEMA, record:identity, status:'unavailable', reason});
738
+ if (!record || !source.projectHash) return unavailable('PLAN_TEXT_RECORD_UNAVAILABLE');
739
+ if (record.path !== 'project.json') return unavailable('PLAN_TEXT_RECORD_UNSUPPORTED');
740
+ const seals = retained.seals.filter(file => file.path === record.path);
741
+ if (record.sha256 !== source.projectHash || seals.length !== 1 || seals[0]!.sha256 !== record.sha256 ||
742
+ isRetainedRecordSource(retained) && (!retained.source.files.some(file => file.path === record.path && file.sha256 === record.sha256) ||
743
+ retained.source.record.path !== record.path || retained.source.record.sha256 !== record.sha256)) {
744
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PLAN_TEXT_RECORD_MISMATCH');
745
+ }
746
+ identity = {path:'project.json', sha256:record.sha256};
747
+ let project: Record<string, unknown>;
748
+ try {project = readProjectRecordBytes(retained.snapshotRoot, identity, true).project;}
749
+ catch (error) {
750
+ if (error instanceof JobError && error.code === 'JOB_RECORD_MOVED')
751
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PLAN_TEXT_RECORD_HASH_MISMATCH');
752
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PLAN_TEXT_RECORD_UNAVAILABLE');
753
+ }
754
+ if (project.schema !== 'rig-create/project@0') return unavailable('PLAN_TEXT_RECORD_UNSUPPORTED');
755
+ if (!Object.hasOwn(project, 'plan')) return unavailable('PLAN_TEXT_STEPS_ABSENT');
756
+ const rawPlan = asPlainObject(project.plan);
757
+ if (!rawPlan) return unavailable('PLAN_TEXT_STEPS_INVALID');
758
+ if (!Object.hasOwn(rawPlan, 'steps')) return unavailable('PLAN_TEXT_STEPS_ABSENT');
759
+ const rawSteps = rawPlan.steps;
760
+ if (!Array.isArray(rawSteps)) return unavailable('PLAN_TEXT_STEPS_INVALID');
761
+ if (plan.steps.length > 4096) return unavailable('PLAN_TEXT_LIMIT');
762
+ if (isRetainedRecordSource(retained) && (rawSteps.length !== plan.steps.length ||
763
+ rawSteps.some((raw, index) => asPlainObject(raw)?.id !== plan.steps[index]?.id)))
764
+ return unavailable('PLAN_TEXT_MAPPING_UNAVAILABLE');
765
+ const wanted = new Set(plan.steps.map(step => step.id));
766
+ const matched = new Map<string, Record<string, unknown> | null>();
767
+ for (const raw of rawSteps) {
768
+ const step = asPlainObject(raw);
769
+ if (typeof step?.id === 'string' && wanted.has(step.id))
770
+ matched.set(step.id, matched.has(step.id) ? null : step);
771
+ }
772
+ if (plan.steps.some(step => !matched.get(step.id))) return unavailable('PLAN_TEXT_MAPPING_UNAVAILABLE');
773
+ const steps = plan.steps.map<JobPlanTextStep>(step => {
774
+ const raw = matched.get(step.id)!;
775
+ const fields: Omit<JobPlanTextStep, 'id' | 'hash' | 'issues'> = {};
776
+ const issues: JobPlanTextStep['issues'] = [];
777
+ for (const field of JOB_PLAN_TEXT_FIELDS) {
778
+ const value = raw[field];
779
+ if (!Object.hasOwn(raw, field)) issues.push({field, reason:'absent'});
780
+ else if (field === 'rests_on') {
781
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) issues.push({field, reason:'invalid'});
782
+ else if (value.length > 4096) issues.push({field, reason:'limit'});
783
+ else fields.rests_on = value;
784
+ } else if (typeof value === 'string') fields[field] = value;
785
+ else issues.push({field, reason:'invalid'});
786
+ }
787
+ return {id:step.id, hash:step.hash, ...fields, issues};
788
+ });
789
+ const projection: JobPlanTextProjection = {schema:JOB_PLAN_TEXT_SCHEMA, record:identity, status:'projected', steps};
790
+ return Buffer.byteLength(JSON.stringify(projection)) > 512 * 1024 ? unavailable('PLAN_TEXT_LIMIT') : projection;
791
+ }
792
+
793
+ /** Keep the normal owner metadata budget, including the small fallback itself. */
794
+ export function planTextMetadata(retained: JobRetainedSourceV3, metadata: Record<string, unknown>): Record<string, unknown> {
795
+ const projection = projectRetainedPlanText(retained);
796
+ if (!projection) return metadata;
797
+ let result = {...metadata, planText:projection};
798
+ if (Buffer.byteLength(JSON.stringify(result)) > 2 * 1024 * 1024) {
799
+ result = {...metadata, planText:{schema:JOB_PLAN_TEXT_SCHEMA, record:projection.record,
800
+ status:'unavailable', reason:'PLAN_TEXT_LIMIT'}};
801
+ if (Buffer.byteLength(JSON.stringify(result)) > 2 * 1024 * 1024)
802
+ throw new JobError('JOB_BODY_LIMIT', 'PLAN_TEXT_LIMIT');
803
+ }
804
+ return result;
805
+ }
806
+
715
807
  function decodeRetainedRecordProject(
716
808
  snapshotRoot: string,
717
809
  seals: readonly JobFileIdentity[],
package/src/parts-view.ts CHANGED
@@ -26,6 +26,8 @@ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } fr
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
+ import {commentsObject, jobSha, jobInteger, parseComments} from './job-api.ts';
30
+ import {PARTS_COMMENTS_VERDICT_SCHEMA, type PartsCommentsVerdict} from './job-contract.ts';
29
31
 
30
32
  export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/4';
31
33
  const LEGACY_VERDICT_SCHEMAS = ['rig-review-parts-verdict/1', 'rig-review-parts-verdict/2', 'rig-review-parts-verdict/3'] as const;
@@ -511,6 +513,36 @@ export interface PartsVerdict {
511
513
  by?: string;
512
514
  }
513
515
 
516
+ /** The standalone comments envelope is a decoder until the consumer activation receipt. */
517
+ export function parseCommentsPartsVerdict(value: unknown): PartsCommentsVerdict {
518
+ const raw = commentsObject(value, ['schema', 'mode', 'tool', 'source', 'status', 'comments', 'updatedAt'], ['by']);
519
+ if (raw.schema !== PARTS_COMMENTS_VERDICT_SCHEMA || typeof raw.mode !== 'string' || !['parts', 'atlas'].includes(raw.mode) ||
520
+ typeof raw.status !== 'string' || !['approved', 'changes-requested'].includes(raw.status)) throw new Error('JOB_ACT_INVALID');
521
+ const tool = commentsObject(raw.tool, ['name', 'version']);
522
+ if (tool.name !== '@rig-c/review' || typeof tool.version !== 'string' || !tool.version) throw new Error('JOB_ACT_INVALID');
523
+ const source = commentsObject(raw.source, ['sha256', 'files', 'flags']);
524
+ jobSha(source.sha256);
525
+ if (!Array.isArray(source.files) || !source.files.length || !Array.isArray(source.flags)) throw new Error('JOB_ACT_INVALID');
526
+ for (const file of source.files) {
527
+ const row = commentsObject(file, ['path', 'sha256', 'bytes']);
528
+ if (typeof row.path !== 'string' || !row.path) throw new Error('JOB_ACT_INVALID');
529
+ jobSha(row.sha256); jobInteger(row.bytes);
530
+ }
531
+ for (const file of source.flags) {
532
+ const row = commentsObject(file, ['path', 'sha256']);
533
+ if (typeof row.path !== 'string' || !row.path) throw new Error('JOB_ACT_INVALID');
534
+ jobSha(row.sha256);
535
+ }
536
+ if (sourceSha256(source.files as HashedFile[]) !== source.sha256) throw new Error('JOB_ACT_INVALID');
537
+ if (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt)) ||
538
+ 'by' in raw && (typeof raw.by !== 'string' || !raw.by)) throw new Error('JOB_ACT_INVALID');
539
+ const comments = parseComments(raw.comments, source.sha256 as string);
540
+ const issues = comments.filter(comment => comment.anchor && 'schema' in comment.anchor).length;
541
+ if (comments.some(comment => comment.anchor && !('schema' in comment.anchor)) ||
542
+ (raw.status === 'approved') !== (issues === 0)) throw new Error('JOB_ACT_INVALID');
543
+ return {...structuredClone(raw), comments} as unknown as PartsCommentsVerdict;
544
+ }
545
+
514
546
  export interface LegacyPartsVerdictView {
515
547
  schema: LegacyVerdictSchema;
516
548
  status: LegacyVerdictStatus;
package/src/session.ts CHANGED
@@ -17,6 +17,64 @@ import { parseReadingsContext } from './readings.ts';
17
17
  import { parseRequirementsContext } from './requirements.ts';
18
18
  import { parseScheduleContext } from './environment-schedule.ts';
19
19
  import { choice, object, string, type Json, type ReviewPackage, type ReviewedSource } from './manifest.ts';
20
+ import { commentsObject, jobSha, parseComments } from './job-api.ts';
21
+ import { REVIEW_COMMENTS_SESSION_SCHEMA, type ReviewCommentsSession } from './job-contract.ts';
22
+
23
+ /** Shared declared provenance decoder. Native source freshness belongs to the package owner. */
24
+ export function parseCommentsReviewedSource(value: unknown): ReviewedSource {
25
+ const source = commentsObject(value, ['packageRevision', 'viewerVersion', 'runtimeVersion', 'rig', 'motion'], ['handoff']);
26
+ for (const key of ['packageRevision', 'viewerVersion', 'runtimeVersion']) string(source[key], `reviewedSource.${key}`);
27
+ for (const key of ['rig', 'motion']) {
28
+ if (source[key] === null) continue;
29
+ const file = commentsObject(source[key], ['path', 'sha256']);
30
+ string(file.path, `reviewedSource.${key}.path`); jobSha(file.sha256);
31
+ }
32
+ if ('handoff' in source) object(source.handoff, 'reviewedSource.handoff');
33
+ return structuredClone(source) as unknown as ReviewedSource;
34
+ }
35
+
36
+ /** The two standalone envelopes share their existing diagnostic row shape. */
37
+ export function parseCommentsWarnings(value: unknown): FeedbackWarning[] {
38
+ if (!Array.isArray(value) || value.length > 1000) throw new Error('JOB_ACT_INVALID');
39
+ for (const warning of value) {
40
+ const row = commentsObject(warning, ['id', 'error']);
41
+ string(row.id, 'warning.id'); string(row.error, 'warning.error');
42
+ }
43
+ return structuredClone(value) as FeedbackWarning[];
44
+ }
45
+
46
+ /** Read-only session/2 decoder. The active UI/save path remains session/1. */
47
+ export function parseCommentsSession(value: unknown): ReviewCommentsSession {
48
+ const raw = commentsObject(value, ['schema', 'id', 'revision', 'sourceHash', 'reviewedSource', 'status',
49
+ 'checkpoints', 'comments', 'feedbackWarnings', 'updatedAt'], ['referenceBinding']);
50
+ if (raw.schema !== REVIEW_COMMENTS_SESSION_SCHEMA) throw new Error('JOB_ACT_INVALID');
51
+ string(raw.id, 'session.id'); string(raw.revision, 'session.revision'); jobSha(raw.sourceHash);
52
+ parseCommentsReviewedSource(raw.reviewedSource);
53
+ choice(raw.status, ['pending', 'approved', 'changes-requested'], 'session.status');
54
+ const checkpoints = object(raw.checkpoints, 'session.checkpoints');
55
+ for (const item of Object.values(checkpoints)) {
56
+ const checkpoint = commentsObject(item, ['outcome']);
57
+ choice(checkpoint.outcome, ['pending', 'pass', 'fail'], 'checkpoint.outcome');
58
+ }
59
+ parseCommentsWarnings(raw.feedbackWarnings);
60
+ if (raw.updatedAt !== null && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt)))) throw new Error('JOB_ACT_INVALID');
61
+ if ('referenceBinding' in raw) {
62
+ const binding = commentsObject(raw.referenceBinding, ['packageSourceHash', 'reference']);
63
+ jobSha(binding.packageSourceHash);
64
+ const reference = commentsObject(binding.reference, ['id', 'name', 'sha256']);
65
+ string(reference.id, 'reference.id'); string(reference.name, 'reference.name'); jobSha(reference.sha256);
66
+ }
67
+ const comments = parseComments(raw.comments, raw.sourceHash as string);
68
+ if (comments.some(comment => comment.anchor && 'side' in comment.anchor)) throw new Error('JOB_ACT_INVALID');
69
+ const reviewed = raw.reviewedSource as unknown as ReviewedSource;
70
+ for (const {anchor} of comments) {
71
+ if (!anchor || !('frameStart' in anchor) || !hasStageComment((anchor.context as any)?.comment)) continue;
72
+ const mark = parseStageComment((anchor.context as any).comment);
73
+ parseBookmark(mark.bookmark, {mode: 'single', sourceHash: raw.sourceHash as string, rigs: [reviewed.rig?.sha256 ?? null]});
74
+ if (!['rig', 'reference'].includes(mark.viewport) || mark.modelHash !== (mark.viewport === 'reference' ? null : reviewed.rig?.sha256 ?? null)) throw new Error('JOB_ACT_INVALID');
75
+ }
76
+ return {...structuredClone(raw), comments} as unknown as ReviewCommentsSession;
77
+ }
20
78
  export interface Feedback {id:string;frameStart:number|null;frameEnd:number|null;target:{kind:'bone'|'slot'|'rig';name:string};category:'defect'|'quality';summary:string;context?:Json}
21
79
  export function parseFeedback(item:unknown,strict=true):Feedback {
22
80
  const f=object(item,'feedback');const target=object(f.target,'feedback.target');
@@ -1,8 +1,37 @@
1
1
  /** Stage marks are optional inspection evidence on an ordinary feedback row. */
2
2
  import type {PosedFrame} from '@rig-c/play';
3
3
  import type {ControlNumericCamera} from './control.ts';
4
+ import type {JobComment, JobCommentAnchor} from './job-contract.ts';
4
5
  export interface MarkPoint {x:number;y:number}
5
6
  export interface MarkRegion {x:number;y:number;width:number;height:number}
7
+
8
+ /** Stable logical labels survive a new Apply capture; raw anchors retain its full evidence. */
9
+ function commentLabel(anchor: JobCommentAnchor): string {
10
+ if ('checkpointId' in anchor) return JSON.stringify(['checkpoint', anchor.checkpointId]);
11
+ if ('schema' in anchor) return JSON.stringify([anchor.schema, anchor.parts.map(part => part.name), anchor.view.mode]);
12
+ if ('name' in anchor) return JSON.stringify([anchor.name]);
13
+ const context = anchor.context as Record<string, unknown> | undefined;
14
+ if (hasStageComment(context?.comment)) {
15
+ const mark = parseStageComment(context!.comment);
16
+ return JSON.stringify([mark.schema, mark.mode, mark.viewport, anchor.target.kind, anchor.target.name,
17
+ anchor.frameStart, anchor.frameEnd]);
18
+ }
19
+ return JSON.stringify([anchor.target.kind, anchor.target.name, anchor.frameStart, anchor.frameEnd,
20
+ 'side' in anchor ? anchor.side : null]);
21
+ }
22
+
23
+ /** The signed scalar projection. Entry text and array order are never normalized. */
24
+ export function projectComments(comments: readonly JobComment[]): string {
25
+ if (!Array.isArray(comments) || comments.length > 1000) throw new Error('JOB_ACT_INVALID');
26
+ const blocks = comments.map(comment => {
27
+ if (!comment || typeof comment.text !== 'string' || !comment.text.trim() || comment.text.length > 10000 ||
28
+ Object.keys(comment).some(key => key !== 'text' && key !== 'anchor')) throw new Error('JOB_ACT_INVALID');
29
+ return `[${comment.anchor === undefined ? 'general' : commentLabel(comment.anchor)}]\n${comment.text}`;
30
+ });
31
+ const text = blocks.join('\n\n');
32
+ if (text.length > 10000) throw new Error('JOB_ACT_INVALID');
33
+ return text;
34
+ }
6
35
  export const commentModes=['setup','animate','compare'] as const;
7
36
  export type CommentMode=typeof commentModes[number];
8
37
  export const timeOnlyReason='frame is unavailable: no explicit producer frame index at this time (COMMENT_FRAME_UNAVAILABLE)' as const;
package/web/catalog-en.ts CHANGED
@@ -89,6 +89,24 @@ export const enCatalog: Readonly<Record<string, string>> = {
89
89
  "interview.other": "Describe your choice",
90
90
  "interview.otherPending": "Other stays pending until a tailored set is offered and explicitly picked.",
91
91
  "interview.autoPending": "Auto stays pending until the agent records the covered decision.",
92
+ "job.plan.does": "Does",
93
+ "job.plan.produces": "Produces",
94
+ "job.plan.bar": "Bar",
95
+ "job.plan.rests_on": "Rests on",
96
+ "job.plan.noText": "Step text is not available; showing ids and hashes.",
97
+ "job.plan.field.absent": "Not supplied in this record.",
98
+ "job.plan.field.invalid": "The supplied field has an unsupported type.",
99
+ "job.plan.field.limit": "The supplied field exceeds the display limit.",
100
+ "PLAN_TEXT_RECORD_UNAVAILABLE": "The retained project record is unavailable.",
101
+ "PLAN_TEXT_RECORD_UNSUPPORTED": "This retained record has no supported project text.",
102
+ "PLAN_TEXT_STEPS_ABSENT": "The record supplies no plan steps.",
103
+ "PLAN_TEXT_STEPS_INVALID": "The record has an unsupported plan step list.",
104
+ "PLAN_TEXT_MAPPING_UNAVAILABLE": "Record steps cannot be matched to the displayed plan.",
105
+ "PLAN_TEXT_LIMIT": "Plan text exceeds the display delivery limit.",
106
+ "PLAN_TEXT_METADATA_INVALID": "Plan text metadata is invalid.",
107
+ "PLAN_TEXT_SOURCE_MISMATCH": "Plan text belongs to a different displayed source.",
108
+ "PLAN_TEXT_RECORD_MISMATCH": "The retained plan record binding differs from the displayed source.",
109
+ "PLAN_TEXT_RECORD_HASH_MISMATCH": "The retained plan record bytes differ from their seal.",
92
110
  "interview.recommended": "AI recommendation",
93
111
  "interview.note": "Note (optional)",
94
112
  "interview.save": "Save explicit picks",
package/web/catalog-ko.ts CHANGED
@@ -89,6 +89,24 @@ export const koCatalog: Readonly<Record<string, string>> = {
89
89
  "interview.other": "원하는 선택을 설명하세요",
90
90
  "interview.otherPending": "맞춤 세트가 제시되고 직접 선택할 때까지 기타 응답은 보류됩니다.",
91
91
  "interview.autoPending": "에이전트가 해당 결정을 기록할 때까지 자동 위임은 보류됩니다.",
92
+ "job.plan.does": "할 일",
93
+ "job.plan.produces": "산출물",
94
+ "job.plan.bar": "기준",
95
+ "job.plan.rests_on": "근거 답변",
96
+ "job.plan.noText": "단계 설명을 읽을 수 없어 ID와 해시만 표시합니다.",
97
+ "job.plan.field.absent": "이 기록에 제공되지 않았습니다.",
98
+ "job.plan.field.invalid": "제공된 필드의 형식을 지원하지 않습니다.",
99
+ "job.plan.field.limit": "제공된 필드가 표시 한도를 초과합니다.",
100
+ "PLAN_TEXT_RECORD_UNAVAILABLE": "보존된 프로젝트 기록을 읽을 수 없습니다.",
101
+ "PLAN_TEXT_RECORD_UNSUPPORTED": "이 보존 기록의 프로젝트 설명 형식을 지원하지 않습니다.",
102
+ "PLAN_TEXT_STEPS_ABSENT": "기록에 계획 단계가 제공되지 않았습니다.",
103
+ "PLAN_TEXT_STEPS_INVALID": "기록의 계획 단계 목록 형식을 지원하지 않습니다.",
104
+ "PLAN_TEXT_MAPPING_UNAVAILABLE": "기록의 단계를 표시된 계획과 연결할 수 없습니다.",
105
+ "PLAN_TEXT_LIMIT": "계획 설명이 표시 전달 한도를 초과합니다.",
106
+ "PLAN_TEXT_METADATA_INVALID": "계획 설명 메타데이터가 올바르지 않습니다.",
107
+ "PLAN_TEXT_SOURCE_MISMATCH": "계획 설명이 표시된 원본과 일치하지 않습니다.",
108
+ "PLAN_TEXT_RECORD_MISMATCH": "보존된 계획 기록의 연결이 표시된 원본과 다릅니다.",
109
+ "PLAN_TEXT_RECORD_HASH_MISMATCH": "보존된 계획 기록의 바이트가 봉인 해시와 다릅니다.",
92
110
  "interview.recommended": "AI 추천",
93
111
  "interview.note": "메모 (선택 사항)",
94
112
  "interview.save": "선택 기록 저장",
@@ -23,6 +23,7 @@ import type {
23
23
  import {enCatalog} from './catalog-en.ts';
24
24
  import {koCatalog} from './catalog-ko.ts';
25
25
  import {t} from './i18n.ts';
26
+ import {JOB_PLAN_TEXT_FIELDS, parseJobPlanTextProjection, type JobPlanTextProjection} from '../src/job-contract.ts';
26
27
  import {JOB_HUB_READY, jobHubMessageMatches, type JobHubBinding} from './job-hub.ts';
27
28
  import {recordJobRigDraw, freezeJobRigCapture, copyJobRigViewport, createJobRigSubmission, jobRigPixelPlacement,
28
29
  type JobRigDraw, type JobRigDrawState} from './job-rig-capture.ts';
@@ -132,6 +133,23 @@ export function prepareJobForms<Form>(
132
133
  return prepared;
133
134
  }
134
135
 
136
+ /** Association checks for normal daemon-authoritative plan text metadata. */
137
+ export function jobPlanTextForSource(value: unknown, source: SourceV3): JobPlanTextProjection | undefined {
138
+ if (value === undefined) return undefined;
139
+ const projection = parseJobPlanTextProjection(value);
140
+ const mismatch = () => {throw new Error('PLAN_TEXT_SOURCE_MISMATCH');};
141
+ if (!source.plan) return mismatch();
142
+ if (projection.record && (projection.record.sha256 !== source.projectHash ||
143
+ isRecordSource(source) && (source.record.path !== projection.record.path ||
144
+ source.record.sha256 !== projection.record.sha256 ||
145
+ !source.files.some(file => file.path === projection.record!.path && file.sha256 === projection.record!.sha256))))
146
+ return mismatch();
147
+ if (projection.status === 'projected' && (projection.steps.length !== source.plan.steps.length ||
148
+ projection.steps.some((row, index) => row.id !== source.plan!.steps[index]?.id || row.hash !== source.plan!.steps[index]?.hash)))
149
+ return mismatch();
150
+ return projection;
151
+ }
152
+
135
153
  /** C2 publishes the plan mapping in the ask. Legacy checkpoint metadata is optional guidance. */
136
154
  export function jobCheckpointContext(
137
155
  ask: PendingAskV3,
@@ -619,6 +637,7 @@ type JobCheckpointEvidenceMetadata = Omit<JobCheckpointEvidence, 'tiles' | 'tabl
619
637
  };
620
638
  export interface JobInspectionMetadata {
621
639
  checkpointEvidence?: readonly JobCheckpointEvidenceMetadata[];
640
+ planText?: JobPlanTextProjection;
622
641
  manifest: ReviewManifest;
623
642
  recordSource?: undefined;
624
643
  sourceHash: string;
@@ -642,6 +661,7 @@ export interface JobInspectionMetadata {
642
661
  }
643
662
  export interface JobRecordInspectionMetadata {
644
663
  checkpointEvidence?: readonly JobCheckpointEvidenceMetadata[];
664
+ planText?: JobPlanTextProjection;
645
665
  manifest?: undefined;
646
666
  recordSource: RecordSource;
647
667
  sourceHash: string;
@@ -859,6 +879,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
859
879
  }
860
880
  const objectUrls: string[] = [];
861
881
  const media: HTMLVideoElement[] = [];
882
+ if (metadata.planText !== undefined) metadata.planText = jobPlanTextForSource(metadata.planText, publishedSource);
862
883
  const rigRoot = document.createElement('div');
863
884
  rigRoot.id = 'rig-root';
864
885
  let assets: ModelAssets | null = null;
@@ -1778,6 +1799,59 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1778
1799
  }
1779
1800
  return gallery;
1780
1801
  }
1802
+ function planTextList(plan: NonNullable<SourceV3['plan']>, projection: JobPlanTextProjection | undefined,
1803
+ selectedId?: string): HTMLElement {
1804
+ const section = node('section');
1805
+ section.className = 'job-plan-text';
1806
+ if (!projection || projection.status === 'unavailable') {
1807
+ section.append(node('p', 'job.plan.noText'));
1808
+ if (projection) section.append(node('p', projection.reason));
1809
+ }
1810
+ const list = node('ol');
1811
+ list.className = 'job-plan-steps';
1812
+ for (const step of plan.steps) {
1813
+ if (selectedId !== undefined && step.id !== selectedId) continue;
1814
+ const item = node('li');
1815
+ item.dataset.jobPlanStep = step.id;
1816
+ const details = node('details');
1817
+ details.open = true;
1818
+ const title = node('summary');
1819
+ title.textContent = step.id;
1820
+ const hash = node('code');
1821
+ hash.className = 'job-source';
1822
+ hash.textContent = step.hash;
1823
+ details.append(title, hash);
1824
+ const row = projection?.status === 'projected' ? projection.steps.find(row => row.id === step.id && row.hash === step.hash) : undefined;
1825
+ if (row) {
1826
+ const fields = node('dl');
1827
+ for (const field of JOB_PLAN_TEXT_FIELDS) {
1828
+ const term = node('dt', 'job.plan.' + field);
1829
+ const value = node('dd');
1830
+ value.dataset.jobPlanField = field;
1831
+ const issue = row.issues.find(issue => issue.field === field);
1832
+ if (issue) value.append(node('span', 'job.plan.field.' + issue.reason));
1833
+ else if (field === 'rests_on') {
1834
+ const rests = node('ul');
1835
+ for (const text of row.rests_on!) {const rest = node('li'); rest.textContent = text; rests.append(rest);}
1836
+ value.append(rests);
1837
+ } else value.textContent = row[field]!;
1838
+ fields.append(term, value);
1839
+ }
1840
+ details.append(fields);
1841
+ }
1842
+ item.append(details); list.append(item);
1843
+ }
1844
+ list.addEventListener('keydown', event => {
1845
+ const key = event as KeyboardEvent;
1846
+ if (!['ArrowUp', 'ArrowDown'].includes(key.key) || !(key.target instanceof HTMLElement) || key.target.tagName !== 'SUMMARY') return;
1847
+ const summaries = [...list.querySelectorAll<HTMLElement>('summary')];
1848
+ const index = summaries.indexOf(key.target);
1849
+ const next = summaries[index + (key.key === 'ArrowDown' ? 1 : -1)];
1850
+ if (next) {key.preventDefault(); next.focus();}
1851
+ });
1852
+ section.append(list);
1853
+ return section;
1854
+ }
1781
1855
  function formFor(ask: PendingAskV3, prepared: JobPreparedInspection): JobForm {
1782
1856
  if (ask.publicationId !== prepared.display.publication.publicationId)
1783
1857
  throw new Error('JOB_DISPLAY_MISMATCH');
@@ -1872,10 +1946,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1872
1946
  fields.prepend(heading);
1873
1947
  const guidance = node('p');
1874
1948
  guidance.textContent = checkpoint.note;
1875
- const planStep = node('p');
1876
- planStep.className = 'job-source';
1877
- planStep.textContent = checkpoint.step.id + ' · ' + checkpoint.step.hash;
1878
- fields.append(planStep, guidance);
1949
+ fields.append(guidance, planTextList(ask.source.plan!, prepared.metadata.planText, checkpoint.step.id));
1879
1950
  const evidence = prepared.checkpointEvidence?.find(item => item.packet.checkpointId === subject.checkpointId);
1880
1951
  const declared = ask.source.checkpointEvidence?.find(item => item.checkpointId === subject.checkpointId);
1881
1952
  if (Boolean(declared) !== Boolean(evidence) || evidence &&
@@ -1930,7 +2001,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1930
2001
  const outcome = selectValues(['', 'pass', 'fail'], ['Pending', 'Pass', 'job.fail']);
1931
2002
  outcome.required = true;
1932
2003
  outcome.name = 'outcome';
1933
- fields.append(outcome);
2004
+ fields.append(outcome, note.parentElement!);
1934
2005
  read = () => ({ checkpointId: subject.checkpointId, outcome: outcome.value as 'pass' | 'fail', words: note.value });
1935
2006
  submitKey = 'job.saveCheckpoint';
1936
2007
  }
@@ -1973,6 +2044,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1973
2044
  const stage = node('p');
1974
2045
  stage.textContent = subject.stage;
1975
2046
  fields.append(stage);
2047
+ if (ask.source.plan) fields.append(planTextList(ask.source.plan, prepared.metadata.planText), note.parentElement!);
1976
2048
  read = () => ({ stage: subject.stage, decision: 'approved', words: note.value });
1977
2049
  submitKey = 'job.signoff';
1978
2050
  }
@@ -2620,14 +2692,8 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
2620
2692
  summary.append(optionLine);
2621
2693
  }
2622
2694
  else {
2623
- const list = node('ol');
2624
- list.className = 'job-source';
2625
- for (const step of source.plan.steps) {
2626
- const item = node('li');
2627
- item.textContent = step.id + ' · ' + step.hash;
2628
- list.append(item);
2629
- }
2630
- summary.append(list);
2695
+ root.dataset.jobPlanWorkspace = '';
2696
+ summary.append(identity, binding, planTextList(source.plan, prepared.metadata.planText));
2631
2697
  }
2632
2698
  stage.prepend(summary);
2633
2699
  controls.hidden = pair.hidden = transport.hidden = true;
package/web/styles.css CHANGED
@@ -498,3 +498,21 @@ body.job-window{display:grid;grid-template-rows:auto auto minmax(0,1fr);height:1
498
498
  .job-window [data-job-checkpoint-evidence] th,.job-window [data-job-checkpoint-evidence] td{padding:6px 10px;border:1px solid var(--border);text-align:left;white-space:pre-wrap;overflow-wrap:anywhere}
499
499
  .job-window [data-job-checkpoint-evidence] caption{text-align:left;margin-bottom:8px}
500
500
  .job-window [data-job-checkpoint-evidence] pre{white-space:pre-wrap;overflow-wrap:anywhere}
501
+
502
+ .job-window .job-plan-text{min-width:0;overflow-wrap:anywhere}
503
+ .job-window .job-plan-steps{padding-left:1.4rem;margin:8px 0}
504
+ .job-window .job-plan-steps>li{margin:8px 0}
505
+ .job-window .job-plan-steps summary{cursor:pointer;font-weight:600;overflow-wrap:anywhere}
506
+ .job-window .job-plan-steps code{display:block;overflow-wrap:anywhere}
507
+ .job-window .job-plan-steps dl{margin:8px 0}
508
+ .job-window .job-plan-steps dt{font-weight:600;margin-top:8px}
509
+ .job-window .job-plan-steps dd{margin:2px 0 8px;white-space:pre-wrap;overflow-wrap:anywhere}
510
+ .job-window .job-plan-steps dd ul{padding-left:1.2rem;margin:0}
511
+
512
+ .job-window .job-inspection[data-job-plan-workspace]{grid-template-columns:minmax(0,1fr) minmax(0,1fr);grid-template-rows:minmax(0,1fr)}
513
+ .job-window .job-inspection[data-job-plan-workspace]>.job-sidebar{display:none}
514
+ .job-window .job-inspection[data-job-plan-workspace]>.job-stage{grid-column:1;grid-row:1;min-width:0;overflow:auto;padding:12px}
515
+ .job-window .job-inspection[data-job-plan-workspace]>.job-forms{grid-column:2;grid-row:1;min-width:0;min-height:0;border-top:0;border-left:1px solid var(--border)}
516
+
517
+ .job-window .job-inspection[data-job-plan-workspace]>.job-stage .job-source,
518
+ .job-window .job-inspection[data-job-plan-workspace]>.job-stage pre{min-width:0;white-space:pre-wrap;overflow-wrap:anywhere}