@rig-c/review 4.8.0 → 4.9.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/STABILITY.md +44 -1
- package/docs/WORKFLOWS.md +10 -0
- package/package.json +2 -2
- package/src/baseline.ts +37 -8
- package/src/job-act-wait.ts +54 -0
- package/src/job-cli.ts +68 -36
- package/src/job-host.ts +2 -0
- package/src/job-session.ts +21 -5
- package/src/rebuild.ts +69 -16
- package/web/catalog-en.ts +1 -0
- package/web/catalog-ko.ts +1 -0
- package/web/i18n.ts +2 -2
- package/web/inspector-blocks.ts +2 -2
- package/web/job-session.ts +4 -1
- package/web/main.ts +6 -3
package/docs/STABILITY.md
CHANGED
|
@@ -516,6 +516,46 @@ constant `JOB_PREVIOUS_DRAFT_SCHEMA` (`rig-review-previous-draft/1`), for twenty
|
|
|
516
516
|
(`rig-review/act@8`), for thirty-one runtime exports total, plus the type-only
|
|
517
517
|
`JobMeshEditValue`, `JobMeshEdit` and `JobMeshEditsAct`.
|
|
518
518
|
|
|
519
|
+
### Host-bound act wait
|
|
520
|
+
|
|
521
|
+
[Review #1005](https://github.com/rig-c/review/issues/1005) adds the host-bound
|
|
522
|
+
finalized-act waiter `waitForJobAct`, for thirty-two runtime exports total, plus
|
|
523
|
+
the type-only `JobActWaitOptions` and `JobActWaitOutcome`.
|
|
524
|
+
|
|
525
|
+
```ts
|
|
526
|
+
function waitForJobAct(host: JobOwnerHost, options: JobActWaitOptions): Promise<JobActWaitOutcome>;
|
|
527
|
+
// options: {after: JobCursor | null; deadlineMs: number; signal?: AbortSignal}
|
|
528
|
+
// outcome: {kind: 'act' | 'closed'; next: JobNextValue | JobNextValueV3; cursor}
|
|
529
|
+
// | {kind: 'timeout'; code: 'JOB_NEXT_TIMEOUT'; next: JobNextValue | JobNextValueV3 | null; cursor}
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
The wait sends the host's own API schema. A package-only host gets
|
|
533
|
+
`rig-review/job-api@2` and answers `JobNextValue` batches. A
|
|
534
|
+
record-and-package host gets `rig-review/job-api@3`, as Create's agents send,
|
|
535
|
+
and answers `JobNextValueV3` batches. An act row there may be a
|
|
536
|
+
`rig-review/act@4` record act (`JobRecordAct`, checked with `parseRecordAct`)
|
|
537
|
+
as well as a package act. The act's own `schema` picks the decoder, so
|
|
538
|
+
`rig-review session next --until act` also accepts record acts from a record
|
|
539
|
+
host. Its output and exit codes are unchanged.
|
|
540
|
+
|
|
541
|
+
It is the `rig-review session next --until act` loop, shared code rather than a
|
|
542
|
+
copy, sent through `host.ports.handleJobApi` with the host's existing agent
|
|
543
|
+
capability. `deadlineMs` is an integer from 1 to 600000. Each server `next`
|
|
544
|
+
stays bounded to 30000 ms, and the wait advances the cursor through unrelated
|
|
545
|
+
publication and ask events. `cursor` is the cursor to resume from. An invalid
|
|
546
|
+
deadline refuses `JOB_REQUEST_INVALID` before any request. A refused `next`
|
|
547
|
+
throws its `JobError` code. Abort rejects with the signal's reason and clears
|
|
548
|
+
the wait's timers. When an empty server window ends less than a millisecond
|
|
549
|
+
before the deadline, the wait sends no zero-wait repeat and sits out the
|
|
550
|
+
remainder. The CLI shares this.
|
|
551
|
+
|
|
552
|
+
A strict `reuseOnly` attachment opens its own read-only session, which the
|
|
553
|
+
live host's in-process notifications never reach. Its `next` therefore watches
|
|
554
|
+
the shared store's revision with the existing 250 ms subscribe watcher, so a
|
|
555
|
+
finalized act the live host commits wakes it. A write that adds no deliverable
|
|
556
|
+
event, such as a display receipt, keeps the wait open, and a refused save
|
|
557
|
+
commits nothing. No API verb, act field or capability changes.
|
|
558
|
+
|
|
519
559
|
The exact runtime exports are listed below. Constants preserve their literal
|
|
520
560
|
values from the frozen semantic contract.
|
|
521
561
|
|
|
@@ -550,6 +590,7 @@ values from the frozen semantic contract.
|
|
|
550
590
|
- `JOB_PLAN_BOUND_SIGNOFF_STAGES`
|
|
551
591
|
- `JOB_CONSUMER_AUTH_MODE`
|
|
552
592
|
- `JOB_ERROR_CODES`
|
|
593
|
+
- `waitForJobAct`
|
|
553
594
|
|
|
554
595
|
The exact type-only exports follow. Their existing definitions in
|
|
555
596
|
`src/job-contract.ts`, `src/job-source.ts`, `src/job-act.ts`, `src/job-session.ts`,
|
|
@@ -566,6 +607,8 @@ without aliases or copied wire shapes.
|
|
|
566
607
|
- `JobSessionOptions`
|
|
567
608
|
- `JobSession`
|
|
568
609
|
- `JobWorkerOptions`
|
|
610
|
+
- `JobActWaitOptions`
|
|
611
|
+
- `JobActWaitOutcome`
|
|
569
612
|
- `JobPublicationReader`
|
|
570
613
|
- `JobPublishedContext`
|
|
571
614
|
- `JobEnabledActKind`
|
|
@@ -723,7 +766,7 @@ Rows are capped at 4096, roles at 128 UTF-16 code units and literal paths at 409
|
|
|
723
766
|
## Installed acceptance
|
|
724
767
|
|
|
725
768
|
`bun run smoke` packs the package and installs that tarball into an empty project.
|
|
726
|
-
A consumer checks the thirty-
|
|
769
|
+
A consumer checks the thirty-two runtime exports and every listed type, including
|
|
727
770
|
`JobHostListenerIncarnation`, `JobHostReuseBinding`, `JobHostReuseExpectation`,
|
|
728
771
|
`JobHostAttachField`, `JobHostAttachFailure`, `JobInterviewJson`,
|
|
729
772
|
`JobInterviewRecord`, `JobInterviewDiagnostic`, `JobInterviewDiagnostics` and
|
package/docs/WORKFLOWS.md
CHANGED
|
@@ -571,6 +571,16 @@ file-only Save has the separate [save-notification contract](PARTS_VIEW.md#durab
|
|
|
571
571
|
Waking this act wait requires a real finalized job act. Consumers use writer-owned `fetch-act` for
|
|
572
572
|
the source-bound result and deduplicate by `actId`.
|
|
573
573
|
|
|
574
|
+
An in-process agent holding a started or strict `reuseOnly` host runs the same wait with
|
|
575
|
+
`waitForJobAct(host, {after, deadlineMs, signal})` from `@rig-c/review/job-host`. It resolves
|
|
576
|
+
`{kind: 'act' | 'closed', next, cursor}` or `{kind: 'timeout', code: 'JOB_NEXT_TIMEOUT', next, cursor}`,
|
|
577
|
+
where `next` is the last accepted batch or `null`, and throws a refused `next` by its `JobError` code.
|
|
578
|
+
On a record-and-package host it speaks `rig-review/job-api@3`, and act rows may be `rig-review/act@4`
|
|
579
|
+
record acts, which this CLI wait also accepts.
|
|
580
|
+
A strict attachment's `next` watches the shared job store, so a finalized act committed by the live
|
|
581
|
+
owner host wakes it within about 250 ms. A write that adds no event, such as a display receipt,
|
|
582
|
+
keeps the wait open. See [Public API stability](STABILITY.md#host-bound-act-wait).
|
|
583
|
+
|
|
574
584
|
- **One standing window and visual gate.** Every owner visual, question, choice, correction and verdict goes through one standing Review window/link plus one what-to-look-at line. Internal agent and HQ media stay internal and are never substituted for the owner handoff. When a required visual is missing (`visual.status` set to `'unavailable'` with a named `code`), the agent stops immediately and files a Create on-path Review card rather than falling back to chat text or images.
|
|
575
585
|
- **Human UI vs agent verbs.** People submit through the Review browser UI (`actor` set to `'human'`, `channel` set to `'review-ui'`). Trusted host bootstrap declares `reviewer` (`id` and `role` as `'owner'` or `'delegate'`), which the browser UI cannot type or override. This binding records bootstrap-declared provenance rather than keyboard-user authentication, and Create maps `role` to its existing `by` authority. Agents use only `publish`, `ask`, `next` and `close` (`JobAgentRequest`), with `expectedGeneration` compare-and-swap (CAS) and `idempotencyKey` on mutations.
|
|
576
586
|
- **Explicit producer-held freeze and explicit close.** Every `publish` request designates a root-relative `result` (`path` and `selector`, never a command) and carries an explicit producer-held freeze (`freeze.kind` set to `'producer-held'`, `holdId`, `record` as `JobFileIdentity` or `null` for a declared non-Create root) held until acknowledgment. Review validates retained bytes, detects a moved record (`JOB_RECORD_MOVED`, `JOB_RECORD_INCOMPLETE`, `JOB_FREEZE_REQUIRED`, `JOB_SOURCE_MISMATCH`, `JOB_SOURCE_UNRETAINABLE`, `JOB_ROOT_REPLACED`) and commits local generation CAS (`JOB_GENERATION_STALE`, `JOB_IDEMPOTENCY_CONFLICT`). The freeze assertion is a caller obligation rather than a lock Review can impose on independent writers. Review offers no watched-root or automatic-close guarantee, and only explicit `close` ends an active job.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rig-c/review",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.9.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local human rig inspection and structured feedback export",
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"pngjs": "7.0.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@rig-c/parts": "2.
|
|
29
|
+
"@rig-c/parts": "2.46.0",
|
|
30
30
|
"@types/bun": "^1.3.0",
|
|
31
31
|
"typescript": "^5.9.3"
|
|
32
32
|
},
|
package/src/baseline.ts
CHANGED
|
@@ -6,8 +6,10 @@
|
|
|
6
6
|
* rebuilds the whole rig may run; otherwise the first differing path is named. Nothing is written into the package.
|
|
7
7
|
*/
|
|
8
8
|
import { createHash } from 'node:crypto';
|
|
9
|
-
import { lstat, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
10
|
-
import { join } from 'node:path';
|
|
9
|
+
import { lstat, mkdir, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
|
10
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
11
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
12
|
+
import { object } from './manifest.ts';
|
|
11
13
|
import type { Handoff } from './handoff.ts';
|
|
12
14
|
import { isProducerFile, PRODUCER_DOCUMENTS, PRODUCER_IMAGES_DIR } from './producer-files.ts';
|
|
13
15
|
import { firstRefusal, runTool, type InstalledTool } from './producer.ts';
|
|
@@ -29,6 +31,8 @@ export interface BaselineResult {
|
|
|
29
31
|
line: string; exitCode: number | null; wallMs: number | null;
|
|
30
32
|
}
|
|
31
33
|
const sha256 = (bytes: Uint8Array | string) => createHash('sha256').update(bytes).digest('hex');
|
|
34
|
+
const RIG_RUN_RECEIPT = 'run.json';
|
|
35
|
+
const RUN_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
32
36
|
async function present(path: string): Promise<boolean> { try { await lstat(path); return true; } catch (e) { if ((e as NodeJS.ErrnoException).code === 'ENOENT') return false; throw e; } }
|
|
33
37
|
|
|
34
38
|
/** A rig directory as {relative path: sha256}: its regular files and images/* (fixed places, not a search). */
|
|
@@ -45,9 +49,12 @@ export const treeHash = (tree: Record<string, string>) => sha256(JSON.stringify(
|
|
|
45
49
|
* file the baseline wrote, and on the inspected side the producer's documents and images (`isProducerFile`; a file there
|
|
46
50
|
* that rig never writes, such as a note, is not the producer's to reproduce).
|
|
47
51
|
*/
|
|
48
|
-
export function firstDifference(baseline: Record<string, string>, inspected: Record<string, string
|
|
49
|
-
const own = Object.keys(inspected).filter(isProducerFile);
|
|
50
|
-
for (const path of [...new Set([...Object.keys(baseline), ...own])].sort())
|
|
52
|
+
export function firstDifference(baseline: Record<string, string>, inspected: Record<string, string>, runReceiptMatches?: boolean): string | null {
|
|
53
|
+
const own = Object.keys(inspected).filter(path => isProducerFile(path) || path === RIG_RUN_RECEIPT);
|
|
54
|
+
for (const path of [...new Set([...Object.keys(baseline), ...own])].sort()) {
|
|
55
|
+
const matches = path === RIG_RUN_RECEIPT && runReceiptMatches !== undefined ? runReceiptMatches : baseline[path] === inspected[path];
|
|
56
|
+
if (!matches) return path;
|
|
57
|
+
}
|
|
51
58
|
if (!Object.keys(baseline).length) return 'rig.json';
|
|
52
59
|
return null;
|
|
53
60
|
}
|
|
@@ -96,9 +103,31 @@ export function assertWholeRigBaseline(result: BaselineResult | null): void {
|
|
|
96
103
|
export const baselineKey = (sourceHash: string, handoff: Handoff, producer: InstalledTool, compiler: InstalledTool) =>
|
|
97
104
|
sha256(JSON.stringify([BASELINE_SCHEMA, sourceHash, handoff.record, `${producer.package}@${producer.version}`, `${compiler.package}@${compiler.version}`]));
|
|
98
105
|
|
|
106
|
+
/** A rig stamp's clock varies per run. Its config path is relative to the output directory. */
|
|
107
|
+
async function runReceiptIdentity(dir: string, rawHash: string): Promise<unknown> {
|
|
108
|
+
try {
|
|
109
|
+
const bytes = await readFile(join(dir, RIG_RUN_RECEIPT));
|
|
110
|
+
if (sha256(bytes) !== rawHash) return null;
|
|
111
|
+
const { started_at, finished_at, ...receipt } = object(JSON.parse(bytes.toString('utf8')), RIG_RUN_RECEIPT);
|
|
112
|
+
if (receipt.spec !== 'rig-run/1' || receipt.command !== 'rig') return null;
|
|
113
|
+
if (![started_at, finished_at].every(time => typeof time === 'string' && RUN_TIMESTAMP.test(time))) return null;
|
|
114
|
+
const { path, ...config } = object(receipt.config, `${RIG_RUN_RECEIPT}.config`);
|
|
115
|
+
if (typeof path !== 'string' || !path || isAbsolute(path)) return null;
|
|
116
|
+
const outputDir = await realpath(dir), configPath = resolve(outputDir, path);
|
|
117
|
+
if (relative(outputDir, configPath).split(sep).join('/') !== path) return null;
|
|
118
|
+
return { ...receipt, config: { ...config, path: configPath } };
|
|
119
|
+
} catch { return null; }
|
|
120
|
+
}
|
|
121
|
+
|
|
99
122
|
/** Compare a finished `<dir>/baseline` with the inspected rig; `show` turns a rig-relative path into the package-relative one. */
|
|
100
123
|
export async function compareBaseline(out: string, inspectedRig: string, show: (rel: string) => string, producerVersion: string | null = null): Promise<Pick<BaselineResult, 'status' | 'firstDifference' | 'hashes' | 'reach'>> {
|
|
101
|
-
const baseline = await rigTree(out),
|
|
124
|
+
const [baseline, inspected] = await Promise.all([rigTree(out), rigTree(inspectedRig)]);
|
|
125
|
+
let runReceiptMatches: boolean | undefined;
|
|
126
|
+
if (baseline[RIG_RUN_RECEIPT] && inspected[RIG_RUN_RECEIPT]) {
|
|
127
|
+
const [a, b] = await Promise.all([runReceiptIdentity(out, baseline[RIG_RUN_RECEIPT]), runReceiptIdentity(inspectedRig, inspected[RIG_RUN_RECEIPT])]);
|
|
128
|
+
runReceiptMatches = a !== null && b !== null && isDeepStrictEqual(a, b);
|
|
129
|
+
}
|
|
130
|
+
const first = firstDifference(baseline, inspected, runReceiptMatches);
|
|
102
131
|
// #148: a build the config does not reproduce says, per op, what the producer will still take.
|
|
103
132
|
const reach = first === null ? null : await baselineReach(out, inspectedRig, baseline, inspected, show, reachOps(producerVersion));
|
|
104
133
|
return { status: first === null ? 'reproduced' : 'not-reproduced', firstDifference: first === null ? null : show(first), hashes: { baseline: { rigJson: baseline['rig.json'] ?? null, tree: treeHash(baseline) }, inspected: { rigJson: inspected['rig.json'] ?? null, tree: treeHash(inspected) } }, reach };
|
|
@@ -135,8 +164,8 @@ export async function runBaseline(dir: string, key: string, handoff: Handoff, pr
|
|
|
135
164
|
|
|
136
165
|
/**
|
|
137
166
|
* The inspected build's own check (#108, HQ ruling): once the baseline reproduces the inspected rig, `rig-parts check`
|
|
138
|
-
*
|
|
139
|
-
*
|
|
167
|
+
* reads the baseline in scratch and writes to `<baseline dir>/inspected-check/` with Apply's default pack flags
|
|
168
|
+
* (`--page-edges free --pack-shape polygon`). The
|
|
140
169
|
* summary is stored beside the baseline record (`inspected-check.json`) so a reload reads it instead of re-running.
|
|
141
170
|
* It is what the physics readout's BEFORE line quotes while the inspected build is on the stage.
|
|
142
171
|
*/
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {type JobCursor, type JobErrorCode, type JobNextValue, type JobNextValueV3} from './job-contract.ts';
|
|
3
|
+
import {jobActWaitLimitMs, waitForActBatch} from './job-cli.ts';
|
|
4
|
+
import type {JobOwnerHost} from './job-front.ts';
|
|
5
|
+
import {JobError} from './job-store.ts';
|
|
6
|
+
|
|
7
|
+
export interface JobActWaitOptions {
|
|
8
|
+
/** Start after this accepted cursor; `null` reads from the first retained event. */
|
|
9
|
+
readonly after: JobCursor | null;
|
|
10
|
+
/** Whole-wait bound in milliseconds, an integer from 1 to 600000 like `job next --until act --wait-ms`. */
|
|
11
|
+
readonly deadlineMs: number;
|
|
12
|
+
/** Caller cancellation. An abort rejects with the signal's reason and clears every timer. */
|
|
13
|
+
readonly signal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The batch carrying the finalized act or the closure, and its cursor to resume from. A
|
|
18
|
+
* package-only host answers `rig-review/job-api@2` batches (`JobNextValue`, package acts);
|
|
19
|
+
* a record-and-package host answers `@3` batches (`JobNextValueV3`), whose act rows may be
|
|
20
|
+
* `rig-review/act@4` record acts (`JobRecordAct`) as well as package acts.
|
|
21
|
+
*/
|
|
22
|
+
type JobActWaitBatch = JobNextValue | JobNextValueV3;
|
|
23
|
+
export type JobActWaitOutcome =
|
|
24
|
+
| {readonly kind: 'act'; readonly next: JobActWaitBatch; readonly cursor: JobCursor | null}
|
|
25
|
+
| {readonly kind: 'closed'; readonly next: JobActWaitBatch; readonly cursor: JobCursor | null}
|
|
26
|
+
| {readonly kind: 'timeout'; readonly code: 'JOB_NEXT_TIMEOUT'; readonly next: JobActWaitBatch | null; readonly cursor: JobCursor | null};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Wait on a started or strictly attached owner host until a finalized act, a closure or the
|
|
30
|
+
* deadline. It is the `job next --until act` loop over the host's own ports with the host's
|
|
31
|
+
* agent capability; a refused `next` throws its `JobError` code.
|
|
32
|
+
*/
|
|
33
|
+
export async function waitForJobAct(host: JobOwnerHost, options: JobActWaitOptions): Promise<JobActWaitOutcome> {
|
|
34
|
+
const {after, deadlineMs, signal} = options;
|
|
35
|
+
if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 1 || deadlineMs > jobActWaitLimitMs ||
|
|
36
|
+
(after !== null && typeof after !== 'string')) throw new JobError('JOB_REQUEST_INVALID');
|
|
37
|
+
const jobId = host.session.jobId, endpoint = `${host.origin}/jobs/${jobId}/api`;
|
|
38
|
+
const capability = host.session.hostCredentials().agent;
|
|
39
|
+
// The host's own API schema: job-api@3 on a record-and-package host, as Create's agents send.
|
|
40
|
+
const result = await waitForActBatch((request, requestSignal) => host.ports.handleJobApi(new Request(endpoint, {
|
|
41
|
+
method: 'POST', signal: requestSignal,
|
|
42
|
+
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability},
|
|
43
|
+
body: JSON.stringify(request),
|
|
44
|
+
})), {schema: host.session.apiSchema, verb: 'next', jobId, requestId: randomUUID(), after, waitMs: 0}, deadlineMs, signal);
|
|
45
|
+
switch (result.kind) {
|
|
46
|
+
case 'act': case 'closed': return {kind: result.kind, next: result.batch, cursor: result.batch.cursor};
|
|
47
|
+
case 'timeout': return {kind: 'timeout', code: 'JOB_NEXT_TIMEOUT', next: result.batch, cursor: result.cursor};
|
|
48
|
+
case 'refused': {
|
|
49
|
+
const error = (result.value as {error?: {code?: unknown; message?: unknown}}).error;
|
|
50
|
+
throw new JobError((typeof error?.code === 'string' ? error.code : 'JOB_REQUEST_INVALID') as JobErrorCode,
|
|
51
|
+
typeof error?.message === 'string' ? error.message : undefined);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
package/src/job-cli.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import {closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync} from 'node:fs';
|
|
3
3
|
import {join} from 'node:path';
|
|
4
4
|
import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, JOB_MESH_EDITS_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, jobRawActMediaType, jobStillByteLimit, jobActDeliveryLimit, jobResponseBodyLimit,
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA,
|
|
6
|
+
type JobAct, type JobMeshEditsAct, type JobAgentRequest, type JobApiSchema, type JobNextRequest, type JobNextRequestV3, type JobNextValue } from './job-contract.ts';
|
|
7
|
+
import { assertJobApiSchema, jobFailure, jobHash, jobId, jobInteger, jobObject, jobWaitLimitMs, parseJobRequest, parseCommentsAct, parseContextCommentsAct, parseMeshEditsAct, parseRecordAct } from './job-api.ts';
|
|
7
8
|
import { JobError } from './job-store.ts';
|
|
8
9
|
import {validatePngBytes} from './comment-crops.ts';
|
|
9
10
|
import {destinationDirectory} from './destination-directory.ts';
|
|
@@ -70,7 +71,7 @@ export function parseJobCLI(args: readonly string[]): { readonly endpoint: strin
|
|
|
70
71
|
if (verb === 'next') {
|
|
71
72
|
let waitMs = Number(values.get('wait-ms') ?? '0');
|
|
72
73
|
if (values.has('until')) {
|
|
73
|
-
if (values.get('until') !== 'act' || !Number.isSafeInteger(waitMs) || waitMs < 1 || waitMs >
|
|
74
|
+
if (values.get('until') !== 'act' || !Number.isSafeInteger(waitMs) || waitMs < 1 || waitMs > jobActWaitLimitMs) {
|
|
74
75
|
throw new JobError('JOB_REQUEST_INVALID');
|
|
75
76
|
}
|
|
76
77
|
waitUntilActMs = waitMs;
|
|
@@ -336,7 +337,8 @@ async function fetchActCommand(args: readonly string[], options: JobCLIOptions):
|
|
|
336
337
|
outputConsumerAct(bytes, png, act, destination, options);
|
|
337
338
|
}
|
|
338
339
|
|
|
339
|
-
async function readJobResponse(response: Response, interrupted?: Promise<never
|
|
340
|
+
async function readJobResponse(response: Response, interrupted?: Promise<never>,
|
|
341
|
+
schema: JobApiSchema = JOB_API_SCHEMA): Promise<unknown> {
|
|
340
342
|
const reader = response.body?.getReader();
|
|
341
343
|
if (!reader) throw new JobError('JOB_REQUEST_INVALID');
|
|
342
344
|
const chunks: Uint8Array[] = [];
|
|
@@ -363,12 +365,12 @@ async function readJobResponse(response: Response, interrupted?: Promise<never>)
|
|
|
363
365
|
let value: unknown;
|
|
364
366
|
try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size))); }
|
|
365
367
|
catch { throw new JobError('JOB_REQUEST_INVALID'); }
|
|
366
|
-
assertJobApiSchema(value !== null && typeof value === 'object' ? (value as { schema?: unknown }).schema : undefined);
|
|
368
|
+
assertJobApiSchema(value !== null && typeof value === 'object' ? (value as { schema?: unknown }).schema : undefined, schema);
|
|
367
369
|
return value;
|
|
368
370
|
}
|
|
369
371
|
|
|
370
372
|
/** Check the complete existing next batch before accepting its read cursor. */
|
|
371
|
-
function nextValue(value: unknown, request: JobNextRequest): JobNextValue {
|
|
373
|
+
function nextValue(value: unknown, request: JobNextRequest | JobNextRequestV3): JobNextValue {
|
|
372
374
|
const result = jobObject(value, ['schema', 'verb', 'jobId', 'requestId', 'generation', 'ok', 'value']);
|
|
373
375
|
if (result.ok !== true || result.verb !== 'next' || result.jobId !== request.jobId) throw new JobError('JOB_REQUEST_INVALID');
|
|
374
376
|
jobInteger(result.generation);
|
|
@@ -383,6 +385,13 @@ function nextValue(value: unknown, request: JobNextRequest): JobNextValue {
|
|
|
383
385
|
switch (event.type) {
|
|
384
386
|
case 'act': {
|
|
385
387
|
const actId = jobId((event.act as {actId?: unknown} | null)?.actId);
|
|
388
|
+
// A record-and-package host also finalizes record acts; the act's own schema picks the decoder.
|
|
389
|
+
if ((event.act as {schema?: unknown}).schema === JOB_RECORD_ACT_SCHEMA) {
|
|
390
|
+
const act = parseRecordAct(event.act);
|
|
391
|
+
if (act.jobId !== request.jobId || act.actId !== actId ||
|
|
392
|
+
!(JOB_RECORD_ACT_KINDS as readonly string[]).includes(act.kind)) throw new JobError('JOB_ACT_INVALID');
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
386
395
|
const act = parseConsumerAct(Buffer.from(JSON.stringify(event.act)), request.jobId, actId);
|
|
387
396
|
if (!(JOB_ENABLED_ACT_KINDS as readonly string[]).includes(act.kind)) throw new JobError('JOB_ACT_INVALID');
|
|
388
397
|
break;
|
|
@@ -406,13 +415,30 @@ function nextValue(value: unknown, request: JobNextRequest): JobNextValue {
|
|
|
406
415
|
return batch as unknown as JobNextValue;
|
|
407
416
|
}
|
|
408
417
|
|
|
409
|
-
|
|
410
|
-
|
|
418
|
+
/** The longest whole act wait an agent may ask for; each server `next` stays within `jobWaitLimitMs`. */
|
|
419
|
+
export const jobActWaitLimitMs = 600_000;
|
|
420
|
+
|
|
421
|
+
/** Outcome of one bounded act wait. `value` is the verbatim accepted response envelope. */
|
|
422
|
+
export type JobActWaitResult =
|
|
423
|
+
| {readonly kind: 'act' | 'closed'; readonly value: unknown; readonly batch: JobNextValue}
|
|
424
|
+
| {readonly kind: 'refused'; readonly value: unknown}
|
|
425
|
+
| {readonly kind: 'timeout'; readonly value: unknown; readonly batch: JobNextValue | null; readonly cursor: string | null};
|
|
426
|
+
|
|
427
|
+
/** One `next` exchange. The transport must honour `signal` and return the response unread. */
|
|
428
|
+
export type JobNextTransport = (request: JobNextRequest | JobNextRequestV3, signal: AbortSignal) => Promise<Response>;
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Transport-independent act wait shared by `job next --until act` and the host-bound
|
|
432
|
+
* `waitForJobAct`: cursor progression, one monotonic deadline, caller cancellation and
|
|
433
|
+
* the act / closed / refusal / timeout outcome. Caller cancellation rejects with its reason.
|
|
434
|
+
*/
|
|
435
|
+
export async function waitForActBatch(send: JobNextTransport, initial: JobNextRequest | JobNextRequestV3, waitMs: number,
|
|
436
|
+
signal?: AbortSignal): Promise<JobActWaitResult> {
|
|
411
437
|
const controller = new AbortController();
|
|
412
438
|
const timeout = new Error('JOB_NEXT_TIMEOUT');
|
|
413
|
-
const cancel = () => controller.abort(
|
|
414
|
-
|
|
415
|
-
if (
|
|
439
|
+
const cancel = () => controller.abort(signal?.reason);
|
|
440
|
+
signal?.addEventListener('abort', cancel, {once: true});
|
|
441
|
+
if (signal?.aborted) cancel();
|
|
416
442
|
const deadline = performance.now() + waitMs;
|
|
417
443
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
418
444
|
const expire = () => {
|
|
@@ -436,16 +462,16 @@ async function waitForAct(endpoint: string, initial: JobNextRequest, waitMs: num
|
|
|
436
462
|
}
|
|
437
463
|
let after = initial.after;
|
|
438
464
|
let lastResponse: unknown;
|
|
465
|
+
let lastBatch: JobNextValue | null = null;
|
|
439
466
|
try {
|
|
440
467
|
for (;;) {
|
|
441
468
|
const budget = remaining();
|
|
442
469
|
const request = {...initial, after, waitMs: Math.max(0, Math.floor(Math.min(budget, jobWaitLimitMs)))};
|
|
470
|
+
// An empty window that ended under a millisecond before the deadline would otherwise
|
|
471
|
+
// repeat zero-wait reads until it; sit out that remainder without another request.
|
|
472
|
+
if (!request.waitMs && lastBatch?.events.length === 0) await interrupted;
|
|
443
473
|
// A delayed transport must also dispose its body if cancellation won the race.
|
|
444
|
-
const pending = (
|
|
445
|
-
method: 'POST', redirect: 'error', signal: controller.signal,
|
|
446
|
-
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability},
|
|
447
|
-
body: JSON.stringify(request),
|
|
448
|
-
}).then(response => {
|
|
474
|
+
const pending = send(request, controller.signal).then(response => {
|
|
449
475
|
if (controller.signal.aborted) {
|
|
450
476
|
try { void response.body?.cancel().catch(() => {}); } catch {}
|
|
451
477
|
controller.signal.throwIfAborted();
|
|
@@ -453,38 +479,44 @@ async function waitForAct(endpoint: string, initial: JobNextRequest, waitMs: num
|
|
|
453
479
|
return response;
|
|
454
480
|
});
|
|
455
481
|
const response = await Promise.race([pending, interrupted]);
|
|
456
|
-
const value = await readJobResponse(response, interrupted);
|
|
482
|
+
const value = await readJobResponse(response, interrupted, initial.schema);
|
|
457
483
|
remaining();
|
|
458
|
-
if (!response.ok || (value as {ok?: unknown}).ok === false) {
|
|
459
|
-
write(JSON.stringify(value));
|
|
460
|
-
process.exitCode = 1;
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
484
|
+
if (!response.ok || (value as {ok?: unknown}).ok === false) return {kind: 'refused', value};
|
|
463
485
|
const batch = nextValue(value, request);
|
|
464
486
|
remaining();
|
|
465
|
-
if (batch.events.some(event => event.type === 'act')) {
|
|
466
|
-
|
|
467
|
-
return;
|
|
468
|
-
}
|
|
469
|
-
if (batch.status === 'closed' || batch.events.some(event => event.type === 'closed')) {
|
|
470
|
-
write(JSON.stringify(value));
|
|
471
|
-
console.error('JOB_CLOSED');
|
|
472
|
-
process.exitCode = 1;
|
|
473
|
-
return;
|
|
474
|
-
}
|
|
487
|
+
if (batch.events.some(event => event.type === 'act')) return {kind: 'act', value, batch};
|
|
488
|
+
if (batch.status === 'closed' || batch.events.some(event => event.type === 'closed')) return {kind: 'closed', value, batch};
|
|
475
489
|
lastResponse = value;
|
|
490
|
+
lastBatch = batch;
|
|
476
491
|
after = batch.cursor;
|
|
477
492
|
}
|
|
478
493
|
} catch (error) {
|
|
479
494
|
if (!controller.signal.aborted && performance.now() >= deadline) controller.abort(timeout);
|
|
480
495
|
if (controller.signal.reason !== timeout) throw error;
|
|
481
|
-
|
|
482
|
-
console.error('JOB_NEXT_TIMEOUT');
|
|
483
|
-
process.exitCode = 3;
|
|
496
|
+
return {kind: 'timeout', value: lastResponse, batch: lastBatch, cursor: after};
|
|
484
497
|
} finally {
|
|
485
498
|
clearTimeout(timer);
|
|
486
|
-
|
|
499
|
+
signal?.removeEventListener('abort', cancel);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async function waitForAct(endpoint: string, initial: JobNextRequest, waitMs: number, capability: string,
|
|
504
|
+
write: (text: string) => void, options: JobCLIOptions): Promise<void> {
|
|
505
|
+
const result = await waitForActBatch((request, signal) => (options.fetch ?? fetch)(endpoint, {
|
|
506
|
+
method: 'POST', redirect: 'error', signal,
|
|
507
|
+
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability},
|
|
508
|
+
body: JSON.stringify(request),
|
|
509
|
+
}), initial, waitMs, options.signal);
|
|
510
|
+
if (result.kind === 'timeout') {
|
|
511
|
+
if (result.value !== undefined) write(JSON.stringify(result.value));
|
|
512
|
+
console.error('JOB_NEXT_TIMEOUT');
|
|
513
|
+
process.exitCode = 3;
|
|
514
|
+
return;
|
|
487
515
|
}
|
|
516
|
+
write(JSON.stringify(result.value));
|
|
517
|
+
if (result.kind === 'act') return;
|
|
518
|
+
if (result.kind === 'closed') console.error('JOB_CLOSED');
|
|
519
|
+
process.exitCode = 1;
|
|
488
520
|
}
|
|
489
521
|
|
|
490
522
|
export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
|
package/src/job-host.ts
CHANGED
|
@@ -10,6 +10,8 @@ export type {
|
|
|
10
10
|
JobHostAttachFailure,
|
|
11
11
|
} from './job-front.ts';
|
|
12
12
|
export type {JobSessionOptions, JobSession} from './job-session.ts';
|
|
13
|
+
export {waitForJobAct} from './job-act-wait.ts';
|
|
14
|
+
export type {JobActWaitOptions, JobActWaitOutcome} from './job-act-wait.ts';
|
|
13
15
|
export type {JobWorkerOptions} from './job-worker.ts';
|
|
14
16
|
export {prepareJobRecordSource} from './job-source.ts';
|
|
15
17
|
export type {
|
package/src/job-session.ts
CHANGED
|
@@ -141,6 +141,8 @@ export class JobSession {
|
|
|
141
141
|
private operations = 0;
|
|
142
142
|
private disposed = false;
|
|
143
143
|
private observedGeneration: number;
|
|
144
|
+
/** A strict attach shares the live host's store but not its in-process listeners. */
|
|
145
|
+
private readonly attached: boolean;
|
|
144
146
|
|
|
145
147
|
/** Last durable generation successfully read by this session. Requires no I/O. */
|
|
146
148
|
get lastObservedGeneration(): number { return this.observedGeneration; }
|
|
@@ -160,6 +162,7 @@ export class JobSession {
|
|
|
160
162
|
}
|
|
161
163
|
this.publicationMode = options.publicationMode ?? (options.readRecordPublished ? 'record-and-package' : 'package-only');
|
|
162
164
|
this.apiSchema = jobApiSchemaForMode(this.publicationMode);
|
|
165
|
+
this.attached = readonlyTarget !== undefined;
|
|
163
166
|
const root = captureJobRoot(options.root), state = canonicalStatePath(options.stateDir);
|
|
164
167
|
if (within(root.path, state)) {
|
|
165
168
|
throw new JobError('JOB_SOURCE_UNRETAINABLE', 'Job state must be outside the designated work root');
|
|
@@ -450,7 +453,8 @@ export class JobSession {
|
|
|
450
453
|
|
|
451
454
|
async execute(input: JobAgentRequest | AgentRequestV3 | JobFetchActRequest | JobFetchActRequestV3, signal: AbortSignal): Promise<unknown> {
|
|
452
455
|
if (input.jobId !== this.jobId) throw new JobError('JOB_UNKNOWN');
|
|
453
|
-
|
|
456
|
+
// An attached session never sees the live host's notify(), so it watches shared writes like subscribe.
|
|
457
|
+
if (input.verb === 'next') return this.next(input.after, input.waitMs, signal, this.attached ? 'events' : false);
|
|
454
458
|
if (input.verb === 'fetch-act') {
|
|
455
459
|
const current = this.current();
|
|
456
460
|
if (!current.active) throw new JobError('JOB_CLOSED');
|
|
@@ -820,11 +824,16 @@ export class JobSession {
|
|
|
820
824
|
};
|
|
821
825
|
}
|
|
822
826
|
|
|
823
|
-
|
|
827
|
+
/**
|
|
828
|
+
* `observeWrites` polls the shared store revision for commits from other sessions. `'revision'` (subscribe)
|
|
829
|
+
* wakes on any commit; `'events'` (an attached act wait) wakes only once a commit left an event to deliver.
|
|
830
|
+
*/
|
|
831
|
+
private async next(after: string | null, waitMs: number, signal: AbortSignal,
|
|
832
|
+
observeWrites: false | 'revision' | 'events' = false): Promise<JobNextValue | NextValueV3> {
|
|
824
833
|
if (waitMs < 0 || waitMs > jobWaitLimitMs || !Number.isSafeInteger(waitMs)) throw new JobError('JOB_REQUEST_INVALID');
|
|
825
834
|
if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
|
|
826
835
|
// Capture before reading events so a commit between the read and listener registration still wakes us.
|
|
827
|
-
|
|
836
|
+
let revision = observeWrites ? this.store.revision(this.jobId) : null;
|
|
828
837
|
const ready = this.events(after);
|
|
829
838
|
if (ready.status !== 'timeout' || !waitMs) return ready;
|
|
830
839
|
await new Promise<void>((resolve, reject) => {
|
|
@@ -835,7 +844,14 @@ export class JobSession {
|
|
|
835
844
|
const fail = (error: unknown) => { if (settled) return; settled = true; cleanup(); reject(error); };
|
|
836
845
|
const abort = () => fail(new JobError('JOB_REQUEST_INVALID', 'Request cancelled'));
|
|
837
846
|
const changed = () => {
|
|
838
|
-
try {
|
|
847
|
+
try {
|
|
848
|
+
const observed = this.store.revision(this.jobId);
|
|
849
|
+
if (observed === revision) return;
|
|
850
|
+
if (observeWrites === 'revision') return finish();
|
|
851
|
+
// An act wait stays open across a write without a deliverable event (display receipt).
|
|
852
|
+
revision = observed;
|
|
853
|
+
if (this.events(after).status !== 'timeout') finish();
|
|
854
|
+
}
|
|
839
855
|
catch (error) { fail(error); }
|
|
840
856
|
};
|
|
841
857
|
const timer = setTimeout(finish, waitMs);
|
|
@@ -858,7 +874,7 @@ export class JobSession {
|
|
|
858
874
|
let after = input.after;
|
|
859
875
|
while (!input.signal.aborted) {
|
|
860
876
|
let value: JobNextValue | NextValueV3;
|
|
861
|
-
try { value = await this.next(after, jobWaitLimitMs, input.signal,
|
|
877
|
+
try { value = await this.next(after, jobWaitLimitMs, input.signal, 'revision'); }
|
|
862
878
|
catch (error) {
|
|
863
879
|
if (input.signal.aborted && error instanceof JobError && error.code === 'JOB_REQUEST_INVALID') return;
|
|
864
880
|
throw error;
|
package/src/rebuild.ts
CHANGED
|
@@ -11,7 +11,8 @@ import {MESH_DELTA_APPLIED_SOURCE,recordFor,type AnyJobView} from '../web/rebuil
|
|
|
11
11
|
* handoff and says whether it reproduces the inspected rig.
|
|
12
12
|
*/
|
|
13
13
|
import { createHash } from 'node:crypto';
|
|
14
|
-
import { existsSync } from 'node:fs';
|
|
14
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
15
|
+
import { createRequire } from 'node:module';
|
|
15
16
|
import { copyFile, mkdir, readFile, readdir, realpath, rename, rm, writeFile, lstat } from 'node:fs/promises';
|
|
16
17
|
import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
|
|
17
18
|
import { object, packagePath, safeFile, type ReviewPackage } from './manifest.ts';
|
|
@@ -549,7 +550,7 @@ export interface ClothJob {
|
|
|
549
550
|
wallMs: { propose: number | null; build: number | null };
|
|
550
551
|
}
|
|
551
552
|
/** #111: what a cloth Apply runs with — the handoff's painting and keypoints (absolute), parts.json and the reader's tags; never from the client. */
|
|
552
|
-
export interface ClothPlan { source: string; keypoints: string; partsJson: unknown; targets: string[] }
|
|
553
|
+
export interface ClothPlan { source: string; keypoints: string; partsJson: unknown; targets: string[]; namedAssembly?: BuildPlan | RebuildError }
|
|
553
554
|
/**
|
|
554
555
|
* The tags the installed reader accepts, read off its own source (`src/cloth.ts`'s `CLOTH_TARGETS`); when that text
|
|
555
556
|
* does not state them, the tags the config's `cloth` block already declares (and `read: false`).
|
|
@@ -922,6 +923,24 @@ async function stageInputDigest(dir:string,spec:string):Promise<string>{
|
|
|
922
923
|
return sha256(JSON.stringify(rows));
|
|
923
924
|
}
|
|
924
925
|
export interface BuildPlan { source: string; full: string; head: string | null; inputsHash: string; inputs: AssembledView['inputs'] }
|
|
926
|
+
const assembledView = (plan: BuildPlan): AssembledView => ({
|
|
927
|
+
inputs: plan.inputs, refusals: [], checkFails: [], lines: [], seam: [], seamPairs: [],
|
|
928
|
+
recomposite: { line: null, before: null, after: null, errorMap: null }, parts: null,
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
/** Read the assembly stamp with the same installation that runs the producer CLI. */
|
|
932
|
+
function clothAssemblyChanges(producer: InstalledTool, config: string, manifest: unknown): string[] {
|
|
933
|
+
if (!hasAssemblyConfig(manifest)) return [];
|
|
934
|
+
const root = realpathSync(producer.root), requireProducer = createRequire(join(root, 'package.json'));
|
|
935
|
+
const reader = realpathSync(requireProducer.resolve('@rig-c/parts/assembly-reading'));
|
|
936
|
+
if (!reader.startsWith(root + sep)) throw new Error('The installed producer does not supply @rig-c/parts/assembly-reading');
|
|
937
|
+
const { assemblyConfigChanges } = requireProducer(reader) as {
|
|
938
|
+
assemblyConfigChanges(config: string, parts: unknown): string[];
|
|
939
|
+
};
|
|
940
|
+
// The successful propose command has already validated its parts manifest.
|
|
941
|
+
return assemblyConfigChanges(config, manifest);
|
|
942
|
+
}
|
|
943
|
+
const hasAssemblyConfig = (manifest: unknown) => !!manifest && typeof manifest === 'object' && Object.hasOwn(manifest, 'assembly_config');
|
|
925
944
|
/**
|
|
926
945
|
* The build's inputs for a patch (`null` refusal line when the handoff declares no painting and full run): the painting
|
|
927
946
|
* and the runs, and every config-relative file the patched config names for assemble, each resolved against the handoff
|
|
@@ -973,6 +992,7 @@ async function hashBuild(build: string, id: string, assetPrefix = '/rebuild'): P
|
|
|
973
992
|
|
|
974
993
|
/** One rebuild at a time per review instance; finished jobs stay readable by id. */
|
|
975
994
|
export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
995
|
+
const handoffBuildPlan = (config: JsonValue) => buildPlan(p.handoff!, config, abs => relative(p.root, abs).split(sep).join('/'));
|
|
976
996
|
const assetPrefix = options.assetPrefix ?? '/rebuild', stripPrefix = options.stripPrefix ?? '/density-strip';
|
|
977
997
|
const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>();
|
|
978
998
|
let running: string | null = null;
|
|
@@ -1639,14 +1659,14 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1639
1659
|
await writeFile(join(dir, 'config.json'), JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
|
|
1640
1660
|
}
|
|
1641
1661
|
/** #111: a cloth job whose written config declares limbs is built as `build` does; otherwise as `rig --config`. */
|
|
1642
|
-
const building = job.op === 'build' ||
|
|
1662
|
+
const building = () => job.op === 'build' || job.cloth?.route === 'build';
|
|
1643
1663
|
/** #115 (and #111's build route): assemble → rig → check on `config.json`, already written into the scratch directory. */
|
|
1644
|
-
async function runBuild(push: (line: string) => void, what: string): Promise<ProcessResult> {
|
|
1664
|
+
async function runBuild(push: (line: string) => void, what: string, { source, full, head }: BuildPlan): Promise<ProcessResult> {
|
|
1645
1665
|
// #112: build forwards `--environment` to its check stage (rig-parts build --help, 1.48.0).
|
|
1646
1666
|
if (world) await writeFile(join(dir, 'environment.json'), world.text, { mode: 0o600 });
|
|
1647
|
-
push(`review: ${producer.package} ${producer.version} build --config config.json (${what}) --source <handoff source> --full <handoff full>${
|
|
1667
|
+
push(`review: ${producer.package} ${producer.version} build --config config.json (${what}) --source <handoff source> --full <handoff full>${head ? ' --head <handoff head>' : ''} --seam-pairs${world ? ` --environment environment.json (the exported schedule, ${world.record.steps} step(s), sha256 ${world.record.sha256.slice(0, 16)})` : ''} → scratch out (assemble → rig → check)`);
|
|
1648
1668
|
// `--seam-pairs` (forwarded to check): the setup-pose seam split by pair on a pass too, so every Apply shows its `seam pair` lines.
|
|
1649
|
-
built = await runTool(producer.bin, ['build', '--config', 'config.json', '--source',
|
|
1669
|
+
built = await runTool(producer.bin, ['build', '--config', 'config.json', '--source', source, '--full', full, ...(head ? ['--head', head] : []), '--out', 'out', '--seam-pairs', ...(world ? ['--environment', 'environment.json'] : []), ...args], { cwd: dir, onLine: push });
|
|
1650
1670
|
const readout = buildReadout(built.lines);
|
|
1651
1671
|
// A check that ran and found a bar not met is check's judgment, kept beside the build (as for a `rig` patch):
|
|
1652
1672
|
// build prints "stopped at check; N bar(s) not met" (a check that refused its input says "no later stage ran").
|
|
@@ -1679,16 +1699,42 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1679
1699
|
}
|
|
1680
1700
|
push(`review: the written config differs from cloth.json at ${c.written.count} path(s), every one under the sections propose splices${c.written.sections.length ? ` (${c.written.sections.join(', ')})` : ''}`);
|
|
1681
1701
|
let op: ProcessResult;
|
|
1682
|
-
if (c.route === 'build') op = await runBuild(push, 'the config propose wrote');
|
|
1702
|
+
if (c.route === 'build') op = await runBuild(push, 'the config propose wrote', plan!);
|
|
1683
1703
|
else {
|
|
1684
|
-
|
|
1685
|
-
|
|
1704
|
+
const changes = clothAssemblyChanges(producer, join(dir, 'config.json'), plan2.partsJson);
|
|
1705
|
+
if (changes.length) {
|
|
1706
|
+
let rebuild: BuildPlan;
|
|
1707
|
+
try {
|
|
1708
|
+
if (plan2.namedAssembly instanceof RebuildError) throw plan2.namedAssembly;
|
|
1709
|
+
rebuild = await handoffBuildPlan(patched);
|
|
1710
|
+
assertNamedFilesHeld(input, written, [dir, ...options.starts]);
|
|
1711
|
+
const held = newBuildFile(input as JsonValue, written as JsonValue);
|
|
1712
|
+
if (held) throw new RebuildError('EDIT_PATCH_PATH_HELD', `${held} names a file the handoff config does not; a patch may not name a new file (review sends no path)`);
|
|
1713
|
+
if (plan2.namedAssembly && rebuild.inputsHash !== plan2.namedAssembly.inputsHash) {
|
|
1714
|
+
throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild');
|
|
1715
|
+
}
|
|
1716
|
+
} catch (error) {
|
|
1717
|
+
if (!(error instanceof RebuildError)) throw error;
|
|
1718
|
+
push(`review: ${error.message}`);
|
|
1719
|
+
return { exitCode: 1, lines: [error.message], stdout: [], wallMs: proposed.wallMs };
|
|
1720
|
+
}
|
|
1721
|
+
c.route = 'build';
|
|
1722
|
+
job.assembled = assembledView(rebuild);
|
|
1723
|
+
op = await runBuild(push, 'the config propose wrote', rebuild);
|
|
1724
|
+
if (op.exitCode === 0 && plan2.namedAssembly && (await handoffBuildPlan(patched)).inputsHash !== rebuild.inputsHash) {
|
|
1725
|
+
throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild');
|
|
1726
|
+
}
|
|
1727
|
+
} else {
|
|
1728
|
+
push(`review: ${producer.package} ${producer.version} rig --config config.json (the config propose wrote) → scratch rig`);
|
|
1729
|
+
op = await runTool(producer.bin, ['rig', '--config', 'config.json', '--parts', inputs.parts, '--out', 'rig', ...args], { cwd: dir, onLine: push });
|
|
1730
|
+
}
|
|
1686
1731
|
}
|
|
1687
1732
|
c.wallMs.build = op.wallMs;
|
|
1688
1733
|
return { ...op, wallMs: proposed.wallMs + op.wallMs };
|
|
1689
1734
|
}
|
|
1690
1735
|
return apply(job, dir, inputs, resolved, {
|
|
1691
|
-
cmd: job.op === 'cloth' ? 'propose' : job.op,
|
|
1736
|
+
cmd: job.op === 'cloth' ? 'propose' : job.op,
|
|
1737
|
+
get spec() { return building() ? 'out/rig' : 'rig'; },
|
|
1692
1738
|
async run(push) {
|
|
1693
1739
|
if (job.op === 'cloth' && cloth) return runCloth(push);
|
|
1694
1740
|
if (job.op === 'build' && plan) {
|
|
@@ -1697,7 +1743,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1697
1743
|
absolutizeBuildFiles(doc, value => (isAbsolute(value) ? value : resolve(dirname(inputs.config), value)));
|
|
1698
1744
|
await stageRequirements(dir, inputs.requirements, doc);
|
|
1699
1745
|
await writeFile(join(dir, 'config.json'), JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
|
|
1700
|
-
return runBuild(push, `the handoff config with ${job.request.patch.ops.length} patch op(s)
|
|
1746
|
+
return runBuild(push, `the handoff config with ${job.request.patch.ops.length} patch op(s)`, plan);
|
|
1701
1747
|
}
|
|
1702
1748
|
if (job.op === 'retune') {
|
|
1703
1749
|
// retune reads the inspected rig and writes only --out; what it holds it refuses by name (RETUNE_REQUEST_HELD).
|
|
@@ -1737,7 +1783,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1737
1783
|
},
|
|
1738
1784
|
wallMs: ms => { job.wallMs.op = ms; },
|
|
1739
1785
|
async flags(push) {
|
|
1740
|
-
if (building && built) {
|
|
1786
|
+
if (building() && built) {
|
|
1741
1787
|
job.exitCode = built.exitCode;
|
|
1742
1788
|
const lines = buildLines(built.lines);
|
|
1743
1789
|
job.producerLine = lines.filter(l => /^build:\s/.test(l)).at(-1) ?? job.producerLine;
|
|
@@ -1762,7 +1808,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1762
1808
|
}, {
|
|
1763
1809
|
diff: files => { const rigJson = files.documents.find(d => d.file === 'rig.json'); job.files = files; job.diff = rigJson ? { count: rigJson.count, paths: rigJson.paths } : null; },
|
|
1764
1810
|
// #115: build runs check itself, on the parts it assembled; its check.json is read after the op (flags).
|
|
1765
|
-
|
|
1811
|
+
get check() {
|
|
1812
|
+
return building() ? undefined : (summary: CheckSummary, wallMs: number | null) => { job.wallMs.check = wallMs; job.check = summary; };
|
|
1813
|
+
},
|
|
1766
1814
|
// #139: a retune Apply reads the check retune ran on its revision (retune.json, bound by its hash rows) unless the
|
|
1767
1815
|
// Apply checks under an exported world (retune's check reads the default one) or the producer carries no line.
|
|
1768
1816
|
// #174: a remesh patch the same, from remesh.json — remesh checked the revision with the request's pack flags,
|
|
@@ -1826,7 +1874,11 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1826
1874
|
if (building) {
|
|
1827
1875
|
const held = newBuildFile(original, patched);
|
|
1828
1876
|
if (held) throw new RebuildError('EDIT_PATCH_PATH_HELD', `${held} names a file the handoff config does not; a patch may not name a new file (review sends no path)`);
|
|
1829
|
-
plan = await
|
|
1877
|
+
plan = await handoffBuildPlan(patched);
|
|
1878
|
+
} else if (clothPlan && p.handoff!.full && hasAssemblyConfig(clothPlan.partsJson) && buildNamedFiles(patched).length) {
|
|
1879
|
+
// These assembly sidecars can sit outside the handoff's hashed run directories. Bind them before scratch reuse.
|
|
1880
|
+
try { clothPlan.namedAssembly = await handoffBuildPlan(patched); }
|
|
1881
|
+
catch (error) { if (!(error instanceof RebuildError)) throw error; clothPlan.namedAssembly = error; }
|
|
1830
1882
|
}
|
|
1831
1883
|
const route = patch.op.cmd === 'remesh' ? 'remesh' : clothing ? 'cloth' : building ? 'build' : patchRoute(patch.ops, resolved.producer.version);
|
|
1832
1884
|
const baselineNow = route === 'retune' ? await settledBaseline() : null;
|
|
@@ -1834,7 +1886,8 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1834
1886
|
if (op === 'rig' || op === 'build' || op === 'cloth') {
|
|
1835
1887
|
try { assertWholeRigBaseline(await settledBaseline()); } catch (e) { if (e instanceof BaselineError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
|
|
1836
1888
|
}
|
|
1837
|
-
const
|
|
1889
|
+
const buildIdentity = plan ?? clothPlan?.namedAssembly;
|
|
1890
|
+
const id = patchId({ sourceHash: p.sourceHash, configHash: rebuildConfigIdentity(inputs), patch, producer: `${resolved.producer.package}@${resolved.producer.version}`, compiler: `${resolved.compiler.package}@${resolved.compiler.version}`, op, ...(buildIdentity && !(buildIdentity instanceof RebuildError) ? { buildInputs: buildIdentity.inputsHash } : {}), ...(world ? { environment: world.record.sha256 } : {}), ...(clothPlan ? { cloth: p.handoff!.record.keypoints!.sha256 } : {}) });
|
|
1838
1891
|
const current = jobs.get(id);
|
|
1839
1892
|
if (current?.status === 'running') return { status: 202, body: snapshot(current) };
|
|
1840
1893
|
if (busy()) return { status: 200, body: { status: 'refused', error: busy(), producerLine: null } };
|
|
@@ -1846,7 +1899,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1846
1899
|
const reused = await reuse<PatchJob>(dir, id);
|
|
1847
1900
|
if (reused) { jobs.set(id, reused); latestId = id; bodies.set(id, body); await landed(reused); return { status: 200, body: snapshot(reused) }; }
|
|
1848
1901
|
const job: PatchJob = { schema: REBUILD_SCHEMA, kind: 'patch', id, status: 'running', reused: false, op, request: { patch, patchSha256: patchSha256(patch), configHash: inputs.configHash }, producer: tool(resolved.producer), compiler: tool(resolved.compiler), lines: [], producerLine: null, exitCode: null, wallMs: { op: null, compile: null, check: null }, check: null, diff: null, files: null, remesh: null, build: null,
|
|
1849
|
-
...(plan ? { assembled:
|
|
1902
|
+
...(plan ? { assembled: assembledView(plan) } : {}),
|
|
1850
1903
|
...(world ? { environment: world.record } : {}),
|
|
1851
1904
|
...(clothPlan ? { cloth: { route: building ? 'build' as const : 'rig' as const, inputs: { source: p.handoff!.record.source?.path ?? '', keypoints: { ...p.handoff!.record.keypoints! } }, refusals: [], line: null, written: null, links: [], wallMs: { propose: null, build: null } } } : {}) };
|
|
1852
1905
|
jobs.set(id, job); running = id; bodies.set(id, body);
|
package/web/catalog-en.ts
CHANGED
|
@@ -3524,6 +3524,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
|
|
|
3524
3524
|
"job.submit.JOB_STILL_UNAVAILABLE": "The retained rig image is unavailable — reopen the current rig review and try again.",
|
|
3525
3525
|
"job.submit.JOB_STILL_OUTPUT_FAILED": "The rig image could not be saved — ask the host operator to check the output destination.",
|
|
3526
3526
|
"Review was not submitted: {0}": "Review was NOT submitted: {0}",
|
|
3527
|
+
"JOB_CAPABILITY_LINK_LOST": "This page lost its access link. Open the original link again to restore access.",
|
|
3527
3528
|
"JOB_CAPABILITY_REQUIRED": "This page has lost its access. Ask the agent to open the job again.",
|
|
3528
3529
|
"JOB_CLOSED": "JOB_CLOSED",
|
|
3529
3530
|
"JOB_CURSOR_INVALID": "JOB_CURSOR_INVALID",
|
package/web/catalog-ko.ts
CHANGED
|
@@ -3524,6 +3524,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
|
|
|
3524
3524
|
"job.submit.JOB_STILL_UNAVAILABLE": "보존된 리그 이미지를 사용할 수 없어요 — 현재 리그 리뷰를 다시 열고 제출해 주세요.",
|
|
3525
3525
|
"job.submit.JOB_STILL_OUTPUT_FAILED": "리그 이미지를 저장하지 못했어요 — 호스트 담당자에게 출력 위치 확인을 요청해 주세요.",
|
|
3526
3526
|
"Review was not submitted: {0}": "리뷰가 제출되지 않았어요: {0}",
|
|
3527
|
+
"JOB_CAPABILITY_LINK_LOST": "이 페이지가 접근 링크를 잃었어요. 처음 받은 링크를 다시 열어 주세요.",
|
|
3527
3528
|
"JOB_CAPABILITY_REQUIRED": "이 페이지의 접근 권한이 만료됐어요. 에이전트에게 작업을 다시 열어 달라고 요청해 주세요.",
|
|
3528
3529
|
"JOB_CLOSED": "JOB_CLOSED",
|
|
3529
3530
|
"JOB_CURSOR_INVALID": "JOB_CURSOR_INVALID",
|
package/web/i18n.ts
CHANGED
|
@@ -972,10 +972,10 @@ export function assertCatalogParity(
|
|
|
972
972
|
// Bar 2: Hardcoded visible string check across web/*.html and web/*.ts
|
|
973
973
|
function decodeHtmlEntities(str: string): string {
|
|
974
974
|
return str
|
|
975
|
-
.replace(/&/g, '&')
|
|
976
975
|
.replace(/</g, '<')
|
|
977
976
|
.replace(/>/g, '>')
|
|
978
|
-
.replace(/"/g, '"')
|
|
977
|
+
.replace(/"/g, '"')
|
|
978
|
+
.replace(/&/g, '&');
|
|
979
979
|
}
|
|
980
980
|
|
|
981
981
|
function isSingleSymbolOrKeycap(text: string): boolean {
|
package/web/inspector-blocks.ts
CHANGED
|
@@ -173,7 +173,7 @@ export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlo
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
/** Compose the real rig acts into C6; all fields, submit nodes and their listeners retain identity. */
|
|
176
|
-
export function mountRigInspector(root:Document=document,actHome?:HTMLElement):BottomPanel&{actBar:ActBar;answersRendered:boolean;syncActRow:()=>void;comments:{button:HTMLButtonElement;panel:HTMLElement}} {
|
|
176
|
+
export function mountRigInspector(root:Document=document,actHome?:HTMLElement):BottomPanel&{body:HTMLElement;actBar:ActBar;answersRendered:boolean;syncActRow:()=>void;comments:{button:HTMLButtonElement;panel:HTMLElement}} {
|
|
177
177
|
const inspector=root.querySelector<HTMLElement>('.inspector')!,body=inspector.querySelector<HTMLElement>('.inspector-body')!,heading=inspector.querySelector<HTMLElement>('.inspector-heading')!;
|
|
178
178
|
const feedback=root.getElementById('inspector-feedback')!,dialog=root.getElementById('review-dialog')!;
|
|
179
179
|
const [label,status,actions]=[feedback.querySelector<HTMLLabelElement>('label[for="review-status"]')!,root.getElementById('review-status')!,dialog.querySelector<HTMLElement>('.review-dialog-actions')!];
|
|
@@ -198,7 +198,7 @@ export function mountRigInspector(root:Document=document,actHome?:HTMLElement):B
|
|
|
198
198
|
// still use this row once its caller has hidden every answer control.
|
|
199
199
|
actHome.hidden=act.hidden||(!question&&!refusal);root.getElementById('dirty')!.hidden=!actHome.hidden;
|
|
200
200
|
};
|
|
201
|
-
return {...bottom,actBar,answersRendered:false,syncActRow,comments:{button:comment,panel:feedback}};
|
|
201
|
+
return {...bottom,body,actBar,answersRendered:false,syncActRow,comments:{button:comment,panel:feedback}};
|
|
202
202
|
}
|
|
203
203
|
|
|
204
204
|
export interface BottomPanel {
|
package/web/job-session.ts
CHANGED
|
@@ -1682,7 +1682,10 @@ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
|
|
|
1682
1682
|
window:{state:()=>window.state(),submit:input=>window.submit(input)},readPublication:(id,signal)=>transport.readPublication(id,signal),
|
|
1683
1683
|
routes:display=>jobPublicationRoutes(display,location.origin),load:async()=>(await import('./main.ts')).mountRigScreen()});
|
|
1684
1684
|
let bootstrapNotice:HTMLElement|null=null,bootstrapStream=false,bootstrapPrior:{text:string;title:string}|null=null;
|
|
1685
|
-
const report=(
|
|
1685
|
+
const report=(failure:unknown,fallback?:string)=>{
|
|
1686
|
+
const reason=failure instanceof Error?failure.message:failure;
|
|
1687
|
+
const error=!access.capability&&reason==='JOB_CAPABILITY_REQUIRED'?'JOB_CAPABILITY_LINK_LOST':failure;
|
|
1688
|
+
const stream=fallback==='JOB_STREAM_FAILED';if(rigScreen.mounted()){rigScreen.report(error,fallback);return;}if(!bootstrapNotice){bootstrapNotice=node('p');bootstrapNotice.setAttribute('role','status');bootstrapNotice.setAttribute('translate','no');host.prepend(bootstrapNotice);}const text=jobWindowRefusal(error,fallback),code=error instanceof Error?error.message:error,title=typeof code==='string'&&/^[A-Z][A-Z0-9_]*$/.test(code)&&Object.hasOwn(enCatalog,code)&&Object.hasOwn(koCatalog,code)?code:fallback??'JOB_WINDOW_FAILED';if(stream)bootstrapStream=true;else{bootstrapStream=false;bootstrapPrior={text,title};}bootstrapNotice.textContent=text;bootstrapNotice.title=title;};
|
|
1686
1689
|
const clear=()=>{rigScreen.clearReport?.();if(!bootstrapStream)return;bootstrapStream=false;if(bootstrapPrior&&bootstrapNotice){bootstrapNotice.textContent=bootstrapPrior.text;bootstrapNotice.title=bootstrapPrior.title;return;}if(bootstrapNotice){bootstrapNotice.textContent='';bootstrapNotice.title='';bootstrapNotice.remove?.();bootstrapNotice=null;}};
|
|
1687
1690
|
const window=createJobWindow<JobRigScreenPrepared|null>({jobId:access.jobId,pageId,transport,adapter:{
|
|
1688
1691
|
async prepare(display,signal){return rigScreen.prepare(display,signal);},
|
package/web/main.ts
CHANGED
|
@@ -340,12 +340,13 @@ function renderDraftState(): void {
|
|
|
340
340
|
function renderProvenance(): void {
|
|
341
341
|
const provenance = session.reviewedSource;
|
|
342
342
|
text('provenance-version', provenance.packageRevision);
|
|
343
|
-
|
|
343
|
+
el('provenance-rig').textContent = provenance.rig ? provenance.rig.sha256.slice(0, 12) + '…' : t('Not supplied');
|
|
344
344
|
el('provenance-motion').hidden = !provenance.motion;
|
|
345
345
|
el('provenance-motion-missing').hidden = !!provenance.motion;
|
|
346
346
|
text('provenance-motion', provenance.motion ? provenance.motion.sha256.slice(0, 12) + '…' : '');
|
|
347
347
|
text('provenance-full', JSON.stringify({ sourceHash: session.sourceHash, referenceBinding:session.referenceBinding, reviewedSource: provenance }, null, 2));
|
|
348
348
|
}
|
|
349
|
+
viewDisposers.push(onLanguageChange(()=>{if(session)renderProvenance();}));
|
|
349
350
|
|
|
350
351
|
function checkpointEntry(): ReviewSession['checkpoints'][string] | undefined {
|
|
351
352
|
if (!checkpoint) return;
|
|
@@ -1309,7 +1310,8 @@ function bindWorkspace(hasModel=false,empty=false):void {
|
|
|
1309
1310
|
}
|
|
1310
1311
|
if(empty)return;
|
|
1311
1312
|
bindReviewDialog();
|
|
1312
|
-
|
|
1313
|
+
// The waiting layout may have moved this body into the inspector drawer.
|
|
1314
|
+
rigInspector.body.append(questionPanel);
|
|
1313
1315
|
inspectorBlocks=bindInspectorBlocks({sections:[el('inspector-rig'),el('inspector-playback')],available:host?.record&&(!host.record.hasPicture||!hasModel&&!partsOnly)?['feedback']:undefined,bottom:{strip:rigInspector.strip,comment:rigInspector.comments.button,panel:rigInspector.comments.panel},changed:()=>{syncQuestionImage();workspace?.refresh();persistence?.save();}});
|
|
1314
1316
|
}
|
|
1315
1317
|
async function start(): Promise<void> {
|
|
@@ -1434,7 +1436,8 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
|
|
|
1434
1436
|
for(const control of document.querySelectorAll<HTMLInputElement|HTMLSelectElement|HTMLButtonElement>('#checkpoint-detail input,#proposal-panel input,#proposal-panel select,#proposal-panel button,#strip-panel input,#strip-panel select,#strip-panel button'))if(!control.closest('#comments-list-host')){control.disabled=true;setSourceAttribute(control,'title',unavailable);if(control instanceof HTMLInputElement&&control.name==='outcome')control.checked=false;}
|
|
1435
1437
|
el('checkpoint-detail').hidden=true;
|
|
1436
1438
|
text('detail-note',unavailable);text('checkpoint-note','');el('strip-panel').hidden=true;
|
|
1437
|
-
text('provenance-version','Parts package, before rigging');
|
|
1439
|
+
const renderPartsProvenance=()=>{text('provenance-version','Parts package, before rigging');el('provenance-rig').textContent=t('Not supplied');el('provenance-motion').hidden=true;el('provenance-motion-missing').hidden=false;text('provenance-motion','');};
|
|
1440
|
+
renderPartsProvenance();viewDisposers.push(onLanguageChange(renderPartsProvenance));
|
|
1438
1441
|
text('provenance-full',JSON.stringify({subject:'parts',sourceHash:subject.sourceHash,painting:subject.painting,images:subject.items.map(({name,imageHash})=>({name,imageHash}))},null,2));
|
|
1439
1442
|
text('source-files',`source ${subject.sourceHash}`);const provenanceHint=document.querySelector<HTMLElement>('.provenance>.hint');if(provenanceHint)setSourceText(provenanceHint,'Source files remain unchanged.');
|
|
1440
1443
|
for(const tab of document.querySelectorAll<HTMLButtonElement>('[data-block-target]'))if(!['selected-part','feedback'].includes(tab.dataset.blockTarget??'')){tab.disabled=true;setSourceAttribute(tab,'title',unavailable);}
|