@rig-c/review 1.16.7 → 1.18.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/README.md +3 -2
- package/docs/DESIGN.md +11 -0
- package/docs/REVIEW_PACKAGE.md +53 -0
- package/docs/STABILITY.md +213 -0
- package/docs/WORKFLOWS.md +52 -0
- package/package.json +11 -9
- package/skills/rig-review/SKILL.md +50 -0
- package/src/entry.ts +59 -0
- package/src/job-act.ts +164 -0
- package/src/job-api.ts +275 -0
- package/src/job-cli.ts +120 -0
- package/src/job-contract.ts +521 -0
- package/src/job-front.ts +443 -0
- package/src/job-host.ts +66 -0
- package/src/job-session.ts +352 -0
- package/src/job-source.ts +291 -0
- package/src/job-store.ts +163 -0
- package/src/job-worker.ts +56 -0
- package/web/catalog-en.ts +66 -0
- package/web/catalog-ko.ts +66 -0
- package/web/job-session.ts +1623 -0
- package/web/parts.ts +28 -19
- package/web/scene-plates.ts +95 -0
- package/web/stage-nav.ts +28 -7
- package/web/styles.css +27 -2
package/src/entry.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/** The legacy CLI keeps every argv and exit contract outside the session namespace. */
|
|
3
|
+
import {writeSync} from 'node:fs';
|
|
4
|
+
import {main as legacyMain} from './cli.ts';
|
|
5
|
+
import {jobCommand, type JobCLIOptions} from './job-cli.ts';
|
|
6
|
+
import {startJobHost} from './job-front.ts';
|
|
7
|
+
import {defaultStateDir, openFingerprint} from './open.ts';
|
|
8
|
+
import {JobError} from './job-store.ts';
|
|
9
|
+
|
|
10
|
+
const sessionUsage = `Usage: rig-review session open <root>
|
|
11
|
+
rig-review session publish <job-url> --generation <n> --key <id> --result <relative-path> --freeze-hold <id> [--selector <JSON>] [--record <path> --record-hash <sha256>]
|
|
12
|
+
rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON>
|
|
13
|
+
rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>]
|
|
14
|
+
rig-review session close <job-url> --generation <n> --key <id> --reason <words>
|
|
15
|
+
Open requires RIG_REVIEW_JOB_REVIEWER_ID and RIG_REVIEW_JOB_REVIEWER_ROLE (owner or delegate).
|
|
16
|
+
RIG_REVIEW_JOB_AGENT_FD optionally delivers the private agent bootstrap on an inherited writable descriptor >= 3.
|
|
17
|
+
Agent verbs use RIG_REVIEW_JOB_AGENT_CAPABILITY. Create's writer binding is installed by its trusted host callback.`;
|
|
18
|
+
|
|
19
|
+
export async function main(args: string[], options: {stateDir?: string; job?: JobCLIOptions} = {}): Promise<void> {
|
|
20
|
+
const sessionArgs = args[0] === 'session' ? args.slice(1) : args[0] === '--' && args[1] === 'session' ? args.slice(2) : null;
|
|
21
|
+
if (!sessionArgs) return legacyMain(args, {stateDir: options.stateDir});
|
|
22
|
+
if (sessionArgs.length === 0 || sessionArgs[0] === '--help' || sessionArgs[0] === '-h') {
|
|
23
|
+
console.log(sessionUsage);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
return jobCommand(sessionArgs, {
|
|
27
|
+
...options.job,
|
|
28
|
+
open: options.job?.open ?? (async root => {
|
|
29
|
+
const id = process.env.RIG_REVIEW_JOB_REVIEWER_ID;
|
|
30
|
+
const role = process.env.RIG_REVIEW_JOB_REVIEWER_ROLE;
|
|
31
|
+
if (!id || role !== 'owner' && role !== 'delegate') throw new JobError('JOB_AUTHORITY_REFUSED');
|
|
32
|
+
const rawPort = process.env.RIG_REVIEW_JOB_PORT;
|
|
33
|
+
const port = rawPort === undefined ? undefined : Number(rawPort);
|
|
34
|
+
if (port !== undefined && (!Number.isSafeInteger(port) || port < 0 || port > 65535)) throw new JobError('JOB_REQUEST_INVALID');
|
|
35
|
+
const rawFD = process.env.RIG_REVIEW_JOB_AGENT_FD;
|
|
36
|
+
const descriptor = rawFD === undefined ? null : Number(rawFD);
|
|
37
|
+
if (descriptor !== null && (!Number.isSafeInteger(descriptor) || descriptor < 3)) throw new JobError('JOB_REQUEST_INVALID');
|
|
38
|
+
const host = await startJobHost({root, stateDir: options.stateDir ?? defaultStateDir(),
|
|
39
|
+
fingerprint: await openFingerprint(), reviewer: {id, role}, port});
|
|
40
|
+
try {
|
|
41
|
+
if (descriptor !== null) {
|
|
42
|
+
writeSync(descriptor, JSON.stringify({jobId: host.session.jobId, origin: host.origin,
|
|
43
|
+
agentCapability: host.session.hostCredentials().agent}) + '\n');
|
|
44
|
+
}
|
|
45
|
+
} catch (error) {host.stop(); throw error;}
|
|
46
|
+
if (!host.reused) {
|
|
47
|
+
const stop = () => {host.stop();};
|
|
48
|
+
process.once('SIGINT', stop);
|
|
49
|
+
process.once('SIGTERM', stop);
|
|
50
|
+
} else host.stop();
|
|
51
|
+
return {ownerUrl: host.ownerUrl};
|
|
52
|
+
}),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (import.meta.main) main(Bun.argv.slice(2)).catch(error => {
|
|
57
|
+
console.error(error instanceof Error ? error.message : error);
|
|
58
|
+
process.exitCode = 1;
|
|
59
|
+
});
|
package/src/job-act.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
JOB_ACT_SCHEMA, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
|
|
4
|
+
type JobAct, type JobActValues, type JobPendingAsk, type JobReviewerBinding,
|
|
5
|
+
type JobSourceBinding, type JobSubject, type JobUISubmission,
|
|
6
|
+
} from './job-contract.ts';
|
|
7
|
+
import { jobId, jobInteger, jobObject, requestDigest } from './job-api.ts';
|
|
8
|
+
import { validatePicks } from './interview-picks.ts';
|
|
9
|
+
import type { JobRetainedSource } from './job-source.ts';
|
|
10
|
+
import { JobError } from './job-store.ts';
|
|
11
|
+
|
|
12
|
+
function words(value: unknown): string {
|
|
13
|
+
if (typeof value !== 'string' || value.length > 10_000) throw new JobError('JOB_ACT_INVALID');
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function choice<Value extends string>(value: unknown, allowed: readonly Value[]): Value {
|
|
18
|
+
if (!allowed.includes(value as Value)) throw new JobError('JOB_ACT_INVALID');
|
|
19
|
+
return value as Value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function requirePlan(source: JobSourceBinding): void {
|
|
23
|
+
if (!source.plan?.steps.length) throw new JobError('JOB_ASK_INVALID', 'Published plan step identities are required');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function bindJobAsk(subject: JobSubject, retained: JobRetainedSource): JobSourceBinding {
|
|
27
|
+
const source = structuredClone(retained.source);
|
|
28
|
+
const declared = retained.subjects.some(candidate => requestDigest(candidate) === requestDigest(subject));
|
|
29
|
+
switch (subject.kind) {
|
|
30
|
+
case 'interview-picks': {
|
|
31
|
+
const question = retained.questions.find(item => item.editable && item.set.question === subject.questionId && item.set.id === subject.setId);
|
|
32
|
+
if (!question) throw new JobError('JOB_ASK_INVALID');
|
|
33
|
+
return { ...source, optionSet: { id: question.set.id, sha256: question.ref.sha256 } };
|
|
34
|
+
}
|
|
35
|
+
case 'checkpoint': {
|
|
36
|
+
requirePlan(source);
|
|
37
|
+
const stepId = subject.planStepId ?? subject.checkpointId;
|
|
38
|
+
if (!declared || !source.plan!.steps.some(step => step.id === stepId)) throw new JobError('JOB_ASK_INVALID');
|
|
39
|
+
return source;
|
|
40
|
+
}
|
|
41
|
+
case 'parts-verdict':
|
|
42
|
+
if (!declared || !source.projectHash || !source.parts || source.selector?.kind !== 'draft' ||
|
|
43
|
+
source.selector.id !== subject.draftId || !retained.partIds.length) throw new JobError('JOB_ASK_INVALID');
|
|
44
|
+
return source;
|
|
45
|
+
case 'review-verdict':
|
|
46
|
+
if (!source.model || (subject.stage === 'rig-review' ? source.selector?.kind !== 'rig' :
|
|
47
|
+
source.selector?.kind !== 'post' || !source.direction)) throw new JobError('JOB_ASK_INVALID');
|
|
48
|
+
return source;
|
|
49
|
+
case 'signoff':
|
|
50
|
+
if (!declared) throw new JobError('JOB_ASK_INVALID');
|
|
51
|
+
if ((JOB_PLAN_BOUND_SIGNOFF_STAGES as readonly string[]).includes(subject.stage)) requirePlan(source);
|
|
52
|
+
return source;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function parseUISubmission(value: unknown): JobUISubmission {
|
|
57
|
+
const item = jobObject(value, ['publicationId', 'askId', 'pageId', 'displayedNonce', 'expectedGeneration', 'submissionId', 'kind', 'value']);
|
|
58
|
+
if ((JOB_RESERVED_ACT_KINDS as readonly unknown[]).includes(item.kind)) throw new JobError('JOB_ACT_KIND_DISABLED');
|
|
59
|
+
jobId(item.publicationId); jobId(item.askId); jobId(item.pageId); jobId(item.displayedNonce); jobId(item.submissionId);
|
|
60
|
+
jobInteger(item.expectedGeneration);
|
|
61
|
+
if (!['interview-picks', 'checkpoint', 'parts-verdict', 'review-verdict', 'signoff'].includes(String(item.kind))) {
|
|
62
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
63
|
+
}
|
|
64
|
+
return item as unknown as JobUISubmission;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Only the authenticated UI host invokes this adapter. All source and authority
|
|
68
|
+
* fields are daemon-owned. Empty/whitespace strings remain exact human words.
|
|
69
|
+
*/
|
|
70
|
+
export function finalizeJobAct(options: {
|
|
71
|
+
readonly jobId: string;
|
|
72
|
+
readonly submission: JobUISubmission;
|
|
73
|
+
readonly ask: JobPendingAsk;
|
|
74
|
+
readonly retained: JobRetainedSource;
|
|
75
|
+
readonly reviewer: JobReviewerBinding;
|
|
76
|
+
}): JobAct {
|
|
77
|
+
const { submission, ask, retained, reviewer } = options;
|
|
78
|
+
if (ask.status !== 'pending') throw new JobError('JOB_ASK_SUPERSEDED');
|
|
79
|
+
if (submission.kind !== ask.subject.kind || submission.publicationId !== ask.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
|
|
80
|
+
const source = bindJobAsk(ask.subject, retained);
|
|
81
|
+
if (requestDigest(source) !== requestDigest(ask.source)) throw new JobError('JOB_ACT_SOURCE_STALE');
|
|
82
|
+
if (!reviewer.id || !['owner', 'delegate'].includes(reviewer.role)) throw new JobError('JOB_AUTHORITY_REFUSED');
|
|
83
|
+
const at = new Date().toISOString();
|
|
84
|
+
const envelope = {
|
|
85
|
+
schema: JOB_ACT_SCHEMA, actId: randomUUID(), jobId: options.jobId, askId: ask.askId,
|
|
86
|
+
publicationId: ask.publicationId,
|
|
87
|
+
authority: { actor: 'human' as const, channel: 'review-ui' as const, reviewer: structuredClone(reviewer) },
|
|
88
|
+
at,
|
|
89
|
+
};
|
|
90
|
+
switch (submission.kind) {
|
|
91
|
+
case 'interview-picks': {
|
|
92
|
+
const value = jobObject(submission.value, ['questionId', 'selections', 'note']);
|
|
93
|
+
const subject = ask.subject;
|
|
94
|
+
if (subject.kind !== 'interview-picks' || value.questionId !== subject.questionId || !Array.isArray(value.selections)) {
|
|
95
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
96
|
+
}
|
|
97
|
+
const question = retained.questions.find(item => item.editable && item.set.id === subject.setId && item.set.question === subject.questionId)!;
|
|
98
|
+
const selections = value.selections.map(raw => {
|
|
99
|
+
const item = jobObject(raw, ['itemId', 'optionId', 'otherText']);
|
|
100
|
+
if (item.otherText !== null && typeof item.otherText !== 'string') throw new JobError('JOB_ACT_INVALID');
|
|
101
|
+
return { itemId: jobId(item.itemId), optionId: jobId(item.optionId), otherText: item.otherText as string | null };
|
|
102
|
+
});
|
|
103
|
+
const note = words(value.note);
|
|
104
|
+
try {
|
|
105
|
+
validatePicks({ schema: 'rig-review/interview-picks@1', set: question.ref, by: 'user', at,
|
|
106
|
+
picks: selections.map(item => ({ ask: item.itemId, option_id: item.optionId,
|
|
107
|
+
...(item.otherText === null ? {} : { other_text: item.otherText }) })), note }, question);
|
|
108
|
+
} catch { throw new JobError('JOB_ACT_INVALID'); }
|
|
109
|
+
return { ...envelope, kind: 'interview-picks', source: { ...source, optionSet: source.optionSet! },
|
|
110
|
+
value: { questionId: subject.questionId, selections, note } };
|
|
111
|
+
}
|
|
112
|
+
case 'checkpoint': {
|
|
113
|
+
const value = jobObject(submission.value, ['checkpointId', 'outcome', 'words']);
|
|
114
|
+
const subject = ask.subject;
|
|
115
|
+
if (subject.kind !== 'checkpoint' || value.checkpointId !== subject.checkpointId) throw new JobError('JOB_ACT_INVALID');
|
|
116
|
+
return { ...envelope, kind: 'checkpoint', source: { ...source, plan: source.plan! }, value: {
|
|
117
|
+
checkpointId: subject.checkpointId, planStepId: subject.planStepId ?? subject.checkpointId,
|
|
118
|
+
outcome: choice(value.outcome, ['pass', 'fail'] as const), words: words(value.words),
|
|
119
|
+
} };
|
|
120
|
+
}
|
|
121
|
+
case 'parts-verdict': {
|
|
122
|
+
const value = jobObject(submission.value, ['verdict', 'parts', 'words']);
|
|
123
|
+
if (!Array.isArray(value.parts) || value.parts.length !== retained.partIds.length) throw new JobError('JOB_ACT_INVALID');
|
|
124
|
+
const ids = new Set<string>();
|
|
125
|
+
const parts = value.parts.map(raw => {
|
|
126
|
+
const item = jobObject(raw, ['partId', 'part', 'mesh']);
|
|
127
|
+
const partId = jobId(item.partId);
|
|
128
|
+
if (!retained.partIds.includes(partId) || ids.has(partId)) throw new JobError('JOB_ACT_INVALID');
|
|
129
|
+
ids.add(partId);
|
|
130
|
+
const outcome = (raw: unknown) => {
|
|
131
|
+
const item = jobObject(raw, ['outcome', 'note']);
|
|
132
|
+
const result = { outcome: choice(item.outcome, ['pending', 'clean', 'flagged'] as const), note: words(item.note) };
|
|
133
|
+
// Match the existing parts verdict writer's flagged-note validation.
|
|
134
|
+
if (result.outcome === 'flagged' && !result.note.trim()) throw new JobError('JOB_ACT_INVALID');
|
|
135
|
+
return result;
|
|
136
|
+
};
|
|
137
|
+
return { partId, part: outcome(item.part), mesh: outcome(item.mesh) };
|
|
138
|
+
});
|
|
139
|
+
const verdict = choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const);
|
|
140
|
+
const outcomes = parts.flatMap(part => [part.part.outcome, part.mesh.outcome]);
|
|
141
|
+
if (verdict === 'approved' && outcomes.some(outcome => outcome !== 'clean') ||
|
|
142
|
+
verdict === 'changes-requested' && !outcomes.includes('flagged')) throw new JobError('JOB_ACT_INVALID');
|
|
143
|
+
return { ...envelope, kind: 'parts-verdict', source: { ...source, projectHash: source.projectHash!,
|
|
144
|
+
selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>, parts: source.parts! },
|
|
145
|
+
value: { verdict, parts, words: words(value.words) } };
|
|
146
|
+
}
|
|
147
|
+
case 'review-verdict': {
|
|
148
|
+
const value = jobObject(submission.value, ['stage', 'verdict', 'words']);
|
|
149
|
+
if (ask.subject.kind !== 'review-verdict' || value.stage !== ask.subject.stage) throw new JobError('JOB_ACT_INVALID');
|
|
150
|
+
return { ...envelope, kind: 'review-verdict', source: { ...source, model: source.model!,
|
|
151
|
+
selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'rig' | 'post' }> }, value: {
|
|
152
|
+
stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words),
|
|
153
|
+
} };
|
|
154
|
+
}
|
|
155
|
+
case 'signoff': {
|
|
156
|
+
const value = jobObject(submission.value, ['stage', 'decision', 'words']);
|
|
157
|
+
if (ask.subject.kind !== 'signoff' || value.stage !== ask.subject.stage || value.decision !== 'approved') {
|
|
158
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
159
|
+
}
|
|
160
|
+
const result: JobActValues['signoff'] = { stage: ask.subject.stage, decision: 'approved', words: words(value.words) };
|
|
161
|
+
return { ...envelope, kind: 'signoff', source, value: result };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
package/src/job-api.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
JOB_API_SCHEMA, JOB_ENABLED_ACT_KINDS, JOB_RESERVED_ACT_KINDS,
|
|
4
|
+
type JobAgentRequest, type JobDisplayAcknowledgment, type JobFetchActRequest,
|
|
5
|
+
type JobHostPorts, type JobResult, type JobSelector, type JobSubject,
|
|
6
|
+
} from './job-contract.ts';
|
|
7
|
+
import { JobError } from './job-store.ts';
|
|
8
|
+
import type { JobSession } from './job-session.ts';
|
|
9
|
+
|
|
10
|
+
export const jobBodyLimit = 256 * 1024;
|
|
11
|
+
export const jobWaitLimitMs = 30_000;
|
|
12
|
+
const requestDeadlineMs = 10_000;
|
|
13
|
+
|
|
14
|
+
export function jobHash(value: string | Uint8Array): string {
|
|
15
|
+
return createHash('sha256').update(value).digest('hex');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Private replay digests only. This is not a mesh payload/source hash format. */
|
|
19
|
+
export function requestDigest(value: unknown): string {
|
|
20
|
+
const sorted = (item: unknown): unknown => {
|
|
21
|
+
if (Array.isArray(item)) return item.map(sorted);
|
|
22
|
+
if (item !== null && typeof item === 'object') {
|
|
23
|
+
return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
24
|
+
.map(([key, child]) => [key, sorted(child)]));
|
|
25
|
+
}
|
|
26
|
+
return item;
|
|
27
|
+
};
|
|
28
|
+
return jobHash(JSON.stringify(sorted(value)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function sameCapability(given: string | null, expected: string): boolean {
|
|
32
|
+
const a = Buffer.from(given ?? '');
|
|
33
|
+
const b = Buffer.from(expected);
|
|
34
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function jobObject(value: unknown, allowed: readonly string[]): Record<string, unknown> {
|
|
38
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value) ||
|
|
39
|
+
Object.keys(value).some(key => !allowed.includes(key))) throw new JobError('JOB_REQUEST_INVALID');
|
|
40
|
+
return value as Record<string, unknown>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function jobText(value: unknown, max = 128): string {
|
|
44
|
+
if (typeof value !== 'string' || !value || value.length > max || /[\x00-\x1f\x7f]/.test(value)) {
|
|
45
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function jobId(value: unknown): string {
|
|
51
|
+
const id = jobText(value);
|
|
52
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) throw new JobError('JOB_REQUEST_INVALID');
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function jobInteger(value: unknown, max = Number.MAX_SAFE_INTEGER): number {
|
|
57
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > max) {
|
|
58
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function jobSha(value: unknown): string {
|
|
64
|
+
if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw new JobError('JOB_REQUEST_INVALID');
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function jobPath(value: unknown): string {
|
|
69
|
+
const path = jobText(value, 4096);
|
|
70
|
+
if (path.split('/').some(part => !part || part === '.' || part === '..') || /[\\:%?#]/.test(path)) {
|
|
71
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
72
|
+
}
|
|
73
|
+
return path;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parseJobSelector(value: unknown): JobSelector | null {
|
|
77
|
+
if (value === null) return null;
|
|
78
|
+
const item = jobObject(value, ['kind', 'id', 'version', 'rigVersion']);
|
|
79
|
+
if (item.kind === 'draft') {
|
|
80
|
+
jobObject(item, ['kind', 'id']);
|
|
81
|
+
return { kind: 'draft', id: jobId(item.id) };
|
|
82
|
+
}
|
|
83
|
+
if (item.kind === 'rig') {
|
|
84
|
+
jobObject(item, ['kind', 'version']);
|
|
85
|
+
const version = jobInteger(item.version);
|
|
86
|
+
if (!version) throw new JobError('JOB_REQUEST_INVALID');
|
|
87
|
+
return { kind: 'rig', version };
|
|
88
|
+
}
|
|
89
|
+
if (item.kind === 'post') {
|
|
90
|
+
jobObject(item, ['kind', 'version', 'rigVersion']);
|
|
91
|
+
const version = jobInteger(item.version), rigVersion = jobInteger(item.rigVersion);
|
|
92
|
+
if (!version || !rigVersion) throw new JobError('JOB_REQUEST_INVALID');
|
|
93
|
+
return { kind: 'post', version, rigVersion };
|
|
94
|
+
}
|
|
95
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function parseJobSubject(value: unknown): JobSubject {
|
|
99
|
+
const item = jobObject(value, ['kind', 'questionId', 'setId', 'checkpointId', 'planStepId', 'draftId', 'stage']);
|
|
100
|
+
if ((JOB_RESERVED_ACT_KINDS as readonly unknown[]).includes(item.kind)) throw new JobError('JOB_ACT_KIND_DISABLED');
|
|
101
|
+
if (!(JOB_ENABLED_ACT_KINDS as readonly unknown[]).includes(item.kind)) throw new JobError('JOB_ASK_INVALID');
|
|
102
|
+
switch (item.kind) {
|
|
103
|
+
case 'interview-picks':
|
|
104
|
+
jobObject(item, ['kind', 'questionId', 'setId']);
|
|
105
|
+
return { kind: item.kind, questionId: jobId(item.questionId), setId: jobId(item.setId) };
|
|
106
|
+
case 'checkpoint':
|
|
107
|
+
jobObject(item, ['kind', 'checkpointId', 'planStepId']);
|
|
108
|
+
return {
|
|
109
|
+
kind: item.kind, checkpointId: jobId(item.checkpointId),
|
|
110
|
+
...(item.planStepId === undefined ? {} : { planStepId: jobId(item.planStepId) }),
|
|
111
|
+
};
|
|
112
|
+
case 'parts-verdict':
|
|
113
|
+
jobObject(item, ['kind', 'draftId']);
|
|
114
|
+
return { kind: item.kind, draftId: jobId(item.draftId) };
|
|
115
|
+
case 'review-verdict':
|
|
116
|
+
jobObject(item, ['kind', 'stage']);
|
|
117
|
+
if (item.stage !== 'rig-review' && item.stage !== 'direction-review') throw new JobError('JOB_ASK_INVALID');
|
|
118
|
+
return { kind: item.kind, stage: item.stage };
|
|
119
|
+
case 'signoff':
|
|
120
|
+
jobObject(item, ['kind', 'stage']);
|
|
121
|
+
return { kind: item.kind, stage: jobId(item.stage) };
|
|
122
|
+
}
|
|
123
|
+
throw new JobError('JOB_ASK_INVALID');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function parseJobRequest(value: unknown): JobAgentRequest | JobFetchActRequest {
|
|
127
|
+
const item = jobObject(value, [
|
|
128
|
+
'schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey',
|
|
129
|
+
'result', 'freeze', 'publicationId', 'subject', 'after', 'waitMs', 'reason', 'actId',
|
|
130
|
+
]);
|
|
131
|
+
if (item.schema !== JOB_API_SCHEMA) throw new JobError('JOB_REQUEST_INVALID');
|
|
132
|
+
const base = { schema: JOB_API_SCHEMA, jobId: jobId(item.jobId), requestId: jobId(item.requestId) };
|
|
133
|
+
if (item.verb === 'next') {
|
|
134
|
+
jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'after', 'waitMs']);
|
|
135
|
+
return { ...base, verb: 'next', after: item.after === null ? null : jobId(item.after), waitMs: jobInteger(item.waitMs, jobWaitLimitMs) };
|
|
136
|
+
}
|
|
137
|
+
if (item.verb === 'fetch-act') {
|
|
138
|
+
jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'actId']);
|
|
139
|
+
return { ...base, verb: 'fetch-act', actId: jobId(item.actId) };
|
|
140
|
+
}
|
|
141
|
+
const mutation = { ...base, expectedGeneration: jobInteger(item.expectedGeneration), idempotencyKey: jobId(item.idempotencyKey) };
|
|
142
|
+
switch (item.verb) {
|
|
143
|
+
case 'publish': {
|
|
144
|
+
jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'result', 'freeze']);
|
|
145
|
+
const result = jobObject(item.result, ['path', 'selector']);
|
|
146
|
+
const freeze = jobObject(item.freeze, ['kind', 'holdId', 'record']);
|
|
147
|
+
if (freeze.kind !== 'producer-held') throw new JobError('JOB_FREEZE_REQUIRED');
|
|
148
|
+
const record = freeze.record === null ? null : jobObject(freeze.record, ['path', 'sha256']);
|
|
149
|
+
return {
|
|
150
|
+
...mutation, verb: 'publish',
|
|
151
|
+
result: { path: jobPath(result.path), selector: parseJobSelector(result.selector) },
|
|
152
|
+
freeze: {
|
|
153
|
+
kind: 'producer-held', holdId: jobId(freeze.holdId),
|
|
154
|
+
record: record === null ? null : { path: jobPath(record.path), sha256: jobSha(record.sha256) },
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
case 'ask':
|
|
159
|
+
jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'publicationId', 'subject']);
|
|
160
|
+
return { ...mutation, verb: 'ask', publicationId: jobId(item.publicationId), subject: parseJobSubject(item.subject) };
|
|
161
|
+
case 'close':
|
|
162
|
+
jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'reason']);
|
|
163
|
+
return { ...mutation, verb: 'close', reason: jobText(item.reason, 1024) };
|
|
164
|
+
}
|
|
165
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function jobBody(request: Request): Promise<unknown> {
|
|
169
|
+
if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type') ?? '')) {
|
|
170
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
171
|
+
}
|
|
172
|
+
const reader = request.body?.getReader();
|
|
173
|
+
if (!reader) throw new JobError('JOB_REQUEST_INVALID');
|
|
174
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
175
|
+
let abort: (() => void) | undefined;
|
|
176
|
+
const interrupted = new Promise<never>((_resolve, reject) => {
|
|
177
|
+
abort = () => reject(new JobError('JOB_REQUEST_INVALID', 'Request cancelled'));
|
|
178
|
+
timer = setTimeout(abort, requestDeadlineMs);
|
|
179
|
+
request.signal.addEventListener('abort', abort, { once: true });
|
|
180
|
+
if (request.signal.aborted) abort();
|
|
181
|
+
});
|
|
182
|
+
try {
|
|
183
|
+
const chunks: Uint8Array[] = [];
|
|
184
|
+
let size = 0;
|
|
185
|
+
for (;;) {
|
|
186
|
+
const { done, value } = await Promise.race([reader.read(), interrupted]);
|
|
187
|
+
if (done) break;
|
|
188
|
+
size += value.length;
|
|
189
|
+
if (size > jobBodyLimit) throw new JobError('JOB_BODY_LIMIT');
|
|
190
|
+
chunks.push(value);
|
|
191
|
+
}
|
|
192
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
void reader.cancel().catch(() => {});
|
|
195
|
+
if (error instanceof JobError) throw error;
|
|
196
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
197
|
+
} finally {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
if (abort) request.signal.removeEventListener('abort', abort);
|
|
200
|
+
reader.releaseLock();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function jobFailure(error: unknown): { ok: false; error: { code: JobError['code']; message: string } } {
|
|
205
|
+
const known = error instanceof JobError ? error : new JobError('JOB_STORAGE_FAILED');
|
|
206
|
+
return { ok: false, error: { code: known.code, message: known.message } };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const responseHeaders = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' };
|
|
210
|
+
|
|
211
|
+
/** The supplied origin is the actual listener origin, not a client header. */
|
|
212
|
+
export function createJobHostPorts(session: JobSession, origin: string): JobHostPorts {
|
|
213
|
+
const parsed = new URL(origin);
|
|
214
|
+
if (parsed.origin !== origin || parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1') {
|
|
215
|
+
throw new JobError('JOB_LOOPBACK_REQUIRED');
|
|
216
|
+
}
|
|
217
|
+
const base = `/jobs/${session.jobId}`;
|
|
218
|
+
function gate(request: Request, path: string, ui: boolean): void {
|
|
219
|
+
const url = new URL(request.url);
|
|
220
|
+
if (url.origin !== origin) throw new JobError('JOB_LOOPBACK_REQUIRED');
|
|
221
|
+
if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) throw new JobError('JOB_REQUEST_INVALID');
|
|
222
|
+
const sent = request.headers.get('origin');
|
|
223
|
+
if (request.headers.get('sec-fetch-site') === 'cross-site' ||
|
|
224
|
+
(ui ? sent !== origin : sent !== null && sent !== origin)) throw new JobError('JOB_SAME_ORIGIN_REQUIRED');
|
|
225
|
+
}
|
|
226
|
+
async function uiCall<Value>(job: string, request: Request, path: string, action: (body: unknown) => Promise<Value>): Promise<JobResult<Value>> {
|
|
227
|
+
try {
|
|
228
|
+
if (job !== session.jobId) throw new JobError('JOB_UNKNOWN');
|
|
229
|
+
gate(request, path, true);
|
|
230
|
+
session.authorize('ui', request.headers.get('X-Review-Capability'));
|
|
231
|
+
return { ok: true, value: await action(await jobBody(request)) };
|
|
232
|
+
} catch (error) { return jobFailure(error); }
|
|
233
|
+
}
|
|
234
|
+
return {
|
|
235
|
+
async handleJobApi(request) {
|
|
236
|
+
let input: JobAgentRequest | JobFetchActRequest | null = null;
|
|
237
|
+
try {
|
|
238
|
+
gate(request, base + '/api', false);
|
|
239
|
+
input = parseJobRequest(await jobBody(request));
|
|
240
|
+
if (input.jobId !== session.jobId) throw new JobError('JOB_UNKNOWN');
|
|
241
|
+
session.authorize(input.verb === 'fetch-act' ? 'consumer' : 'agent', request.headers.get('authorization'));
|
|
242
|
+
const value = await session.execute(input, request.signal);
|
|
243
|
+
return Response.json({ schema: JOB_API_SCHEMA, verb: input.verb, jobId: input.jobId, requestId: input.requestId,
|
|
244
|
+
generation: session.status().generation, ok: true, value }, { headers: responseHeaders });
|
|
245
|
+
} catch (error) {
|
|
246
|
+
const failure = jobFailure(error);
|
|
247
|
+
const status = failure.error.code.includes('CAPABILITY') || failure.error.code === 'JOB_AUTHORITY_REFUSED' ? 403 :
|
|
248
|
+
failure.error.code === 'JOB_BODY_LIMIT' ? 413 : failure.error.code === 'JOB_REQUEST_INVALID' ? 400 : 409;
|
|
249
|
+
return Response.json({ schema: JOB_API_SCHEMA, verb: input?.verb ?? null, jobId: session.jobId,
|
|
250
|
+
requestId: input?.requestId ?? null, generation: session.status().generation, ...failure }, { status, headers: responseHeaders });
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
subscribeJob: input => session.subscribe(input),
|
|
254
|
+
async readPublication(job, publication) {
|
|
255
|
+
try {
|
|
256
|
+
if (job !== session.jobId) throw new JobError('JOB_UNKNOWN');
|
|
257
|
+
return { ok: true, value: session.displayPublication(publication) };
|
|
258
|
+
} catch (error) { return jobFailure(error); }
|
|
259
|
+
},
|
|
260
|
+
commitUIAct: (job, request) => uiCall(job, request, base + '/ui/acts', body => session.commitUIAct(body)),
|
|
261
|
+
ackDisplayed: (job, request) => uiCall(job, request, base + '/ui/displayed', async body => {
|
|
262
|
+
const item = jobObject(body, ['publicationId', 'pageId', 'sourceHash']);
|
|
263
|
+
const ack: JobDisplayAcknowledgment = {
|
|
264
|
+
publicationId: jobId(item.publicationId), pageId: jobId(item.pageId), sourceHash: jobSha(item.sourceHash),
|
|
265
|
+
};
|
|
266
|
+
return session.ackDisplayed(ack);
|
|
267
|
+
}),
|
|
268
|
+
async jobLiveness(job) {
|
|
269
|
+
try {
|
|
270
|
+
if (job !== session.jobId) throw new JobError('JOB_UNKNOWN');
|
|
271
|
+
return { ok: true, value: { active: session.status().status === 'active', busy: session.busy } };
|
|
272
|
+
} catch (error) { return jobFailure(error); }
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
package/src/job-cli.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { JOB_API_SCHEMA, type JobAgentRequest } from './job-contract.ts';
|
|
3
|
+
import { jobFailure, parseJobRequest } from './job-api.ts';
|
|
4
|
+
import { JobError } from './job-store.ts';
|
|
5
|
+
|
|
6
|
+
export interface JobCLIOptions {
|
|
7
|
+
readonly agentCapability?: string;
|
|
8
|
+
/** Lane B owns managed-front startup and the owner link. The host binds the
|
|
9
|
+
* reviewer identity and separately delivers credentials. No registry read or
|
|
10
|
+
* consumer grant is exposed by this agent-facing CLI.
|
|
11
|
+
*/
|
|
12
|
+
readonly open?: (root: string) => Promise<{ readonly ownerUrl: string }>;
|
|
13
|
+
readonly fetch?: typeof fetch;
|
|
14
|
+
readonly signal?: AbortSignal;
|
|
15
|
+
readonly write?: (text: string) => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const commonFlags = ['generation', 'key', 'request-id'];
|
|
19
|
+
const verbFlags: Record<string, readonly string[]> = {
|
|
20
|
+
publish: [...commonFlags, 'result', 'selector', 'freeze-hold', 'record', 'record-hash'],
|
|
21
|
+
ask: [...commonFlags, 'publication', 'subject'],
|
|
22
|
+
next: ['after', 'wait-ms', 'request-id'],
|
|
23
|
+
close: [...commonFlags, 'reason'],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function flags(args: readonly string[], allowed: readonly string[]): Map<string, string> {
|
|
27
|
+
const result = new Map<string, string>();
|
|
28
|
+
for (let index = 0; index < args.length; index += 2) {
|
|
29
|
+
const name = args[index]?.replace(/^--/, '');
|
|
30
|
+
if (!args[index]?.startsWith('--') || !name || !allowed.includes(name) || result.has(name) || args[index + 1] === undefined) {
|
|
31
|
+
throw new JobError('JOB_REQUEST_INVALID');
|
|
32
|
+
}
|
|
33
|
+
result.set(name, args[index + 1]);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function required(values: Map<string, string>, key: string): string {
|
|
39
|
+
const value = values.get(key);
|
|
40
|
+
if (value === undefined) throw new JobError('JOB_REQUEST_INVALID');
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function semanticJSON(value: string): unknown {
|
|
45
|
+
try { return JSON.parse(value); }
|
|
46
|
+
catch { throw new JobError('JOB_REQUEST_INVALID'); }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Public semantic request construction only. There is no act-writing or
|
|
50
|
+
* consumer-fetch verb, no internal JSON input file and no Review state access.
|
|
51
|
+
*/
|
|
52
|
+
export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest } {
|
|
53
|
+
const [verb, locator, ...rest] = args;
|
|
54
|
+
if (!verbFlags[verb]) throw new JobError('JOB_REQUEST_INVALID');
|
|
55
|
+
let url: URL;
|
|
56
|
+
try { url = new URL(locator); }
|
|
57
|
+
catch { throw new JobError('JOB_REQUEST_INVALID'); }
|
|
58
|
+
const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.pathname);
|
|
59
|
+
if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash || !match) {
|
|
60
|
+
throw new JobError('JOB_LOOPBACK_REQUIRED');
|
|
61
|
+
}
|
|
62
|
+
const values = flags(rest, verbFlags[verb]);
|
|
63
|
+
const base = { schema: JOB_API_SCHEMA, verb, jobId: match[1], requestId: values.get('request-id') ?? randomUUID() };
|
|
64
|
+
let payload: unknown;
|
|
65
|
+
if (verb === 'next') {
|
|
66
|
+
payload = { ...base, after: values.get('after') ?? null, waitMs: Number(values.get('wait-ms') ?? '0') };
|
|
67
|
+
} else {
|
|
68
|
+
const mutation = { ...base, expectedGeneration: Number(required(values, 'generation')), idempotencyKey: required(values, 'key') };
|
|
69
|
+
switch (verb) {
|
|
70
|
+
case 'publish': {
|
|
71
|
+
const recordPath = values.get('record'), recordHash = values.get('record-hash');
|
|
72
|
+
if ((recordPath === undefined) !== (recordHash === undefined)) throw new JobError('JOB_REQUEST_INVALID');
|
|
73
|
+
payload = { ...mutation, result: { path: required(values, 'result'), selector: semanticJSON(values.get('selector') ?? 'null') },
|
|
74
|
+
freeze: { kind: 'producer-held', holdId: required(values, 'freeze-hold'),
|
|
75
|
+
record: recordPath === undefined ? null : { path: recordPath, sha256: recordHash } } };
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case 'ask':
|
|
79
|
+
payload = { ...mutation, publicationId: required(values, 'publication'), subject: semanticJSON(required(values, 'subject')) };
|
|
80
|
+
break;
|
|
81
|
+
case 'close':
|
|
82
|
+
payload = { ...mutation, reason: required(values, 'reason') };
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const request = parseJobRequest(payload);
|
|
87
|
+
if (request.verb === 'fetch-act') throw new JobError('JOB_AUTHORITY_REFUSED');
|
|
88
|
+
return { endpoint: `${url.origin}/jobs/${match[1]}/api`, request };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
|
|
92
|
+
const write = options.write ?? (text => console.log(text));
|
|
93
|
+
if (args[0] === 'open') {
|
|
94
|
+
if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
|
|
95
|
+
write((await options.open(args[1])).ownerUrl);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const input = parseJobCLI(args);
|
|
99
|
+
const capability = options.agentCapability ?? process.env.RIG_REVIEW_JOB_AGENT_CAPABILITY;
|
|
100
|
+
if (!capability) throw new JobError('JOB_CAPABILITY_REQUIRED');
|
|
101
|
+
const response = await (options.fetch ?? fetch)(input.endpoint, {
|
|
102
|
+
method: 'POST', redirect: 'error', signal: options.signal,
|
|
103
|
+
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + capability },
|
|
104
|
+
body: JSON.stringify(input.request),
|
|
105
|
+
});
|
|
106
|
+
const bytes = await response.arrayBuffer();
|
|
107
|
+
if (bytes.byteLength > 1024 * 1024) throw new JobError('JOB_BODY_LIMIT');
|
|
108
|
+
let value: unknown;
|
|
109
|
+
try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
|
|
110
|
+
catch { throw new JobError('JOB_REQUEST_INVALID'); }
|
|
111
|
+
write(JSON.stringify(value));
|
|
112
|
+
if (!response.ok) process.exitCode = 1;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (import.meta.main) {
|
|
116
|
+
jobCommand(Bun.argv.slice(2)).catch(error => {
|
|
117
|
+
console.error(JSON.stringify(jobFailure(error)));
|
|
118
|
+
process.exitCode = 1;
|
|
119
|
+
});
|
|
120
|
+
}
|