@dsh-ray/assistant-verifier 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +286 -2
- package/cordis.patch.yml +10 -0
- package/lib/config.d.ts +47 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +82 -0
- package/lib/config.js.map +1 -0
- package/lib/creation-review-native.d.ts +30 -0
- package/lib/creation-review-native.d.ts.map +1 -0
- package/lib/creation-review-native.js +137 -0
- package/lib/creation-review-native.js.map +1 -0
- package/lib/creation-review-store.d.ts +108 -0
- package/lib/creation-review-store.d.ts.map +1 -0
- package/lib/creation-review-store.js +715 -0
- package/lib/creation-review-store.js.map +1 -0
- package/lib/creation-review.d.ts +317 -0
- package/lib/creation-review.d.ts.map +1 -0
- package/lib/creation-review.js +842 -0
- package/lib/creation-review.js.map +1 -0
- package/lib/drivers.d.ts +153 -0
- package/lib/drivers.d.ts.map +1 -0
- package/lib/drivers.js +825 -0
- package/lib/drivers.js.map +1 -0
- package/lib/host.d.ts +93 -0
- package/lib/host.d.ts.map +1 -0
- package/lib/host.js +2 -0
- package/lib/host.js.map +1 -0
- package/lib/index.d.ts +26 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +18 -0
- package/lib/index.js.map +1 -0
- package/lib/linux-behavior-assets.d.ts +17 -0
- package/lib/linux-behavior-assets.d.ts.map +1 -0
- package/lib/linux-behavior-assets.js +73 -0
- package/lib/linux-behavior-assets.js.map +1 -0
- package/lib/linux-behavior-runner.d.ts +10 -0
- package/lib/linux-behavior-runner.d.ts.map +1 -0
- package/lib/linux-behavior-runner.js +69 -0
- package/lib/linux-behavior-runner.js.map +1 -0
- package/lib/linux-behavior-runtime.d.ts +67 -0
- package/lib/linux-behavior-runtime.d.ts.map +1 -0
- package/lib/linux-behavior-runtime.js +500 -0
- package/lib/linux-behavior-runtime.js.map +1 -0
- package/lib/memory-review-native.d.ts +50 -0
- package/lib/memory-review-native.d.ts.map +1 -0
- package/lib/memory-review-native.js +166 -0
- package/lib/memory-review-native.js.map +1 -0
- package/lib/memory-review.d.ts +50 -0
- package/lib/memory-review.d.ts.map +1 -0
- package/lib/memory-review.js +363 -0
- package/lib/memory-review.js.map +1 -0
- package/lib/native-behavior-artifact.d.ts +9 -0
- package/lib/native-behavior-artifact.d.ts.map +1 -0
- package/lib/native-behavior-artifact.js +144 -0
- package/lib/native-behavior-artifact.js.map +1 -0
- package/lib/native-behavior-worker.d.ts +3 -0
- package/lib/native-behavior-worker.d.ts.map +1 -0
- package/lib/native-behavior-worker.js +453 -0
- package/lib/native-behavior-worker.js.map +1 -0
- package/lib/plugin-behavior-config.d.ts +34 -0
- package/lib/plugin-behavior-config.d.ts.map +1 -0
- package/lib/plugin-behavior-config.js +170 -0
- package/lib/plugin-behavior-config.js.map +1 -0
- package/lib/plugin-behavior-runner.d.ts +57 -0
- package/lib/plugin-behavior-runner.d.ts.map +1 -0
- package/lib/plugin-behavior-runner.js +910 -0
- package/lib/plugin-behavior-runner.js.map +1 -0
- package/lib/review-authority-lineage.d.ts +109 -0
- package/lib/review-authority-lineage.d.ts.map +1 -0
- package/lib/review-authority-lineage.js +135 -0
- package/lib/review-authority-lineage.js.map +1 -0
- package/lib/review-maintenance.d.ts +20 -0
- package/lib/review-maintenance.d.ts.map +1 -0
- package/lib/review-maintenance.js +24 -0
- package/lib/review-maintenance.js.map +1 -0
- package/lib/revision-regression-review.d.ts +41 -0
- package/lib/revision-regression-review.d.ts.map +1 -0
- package/lib/revision-regression-review.js +379 -0
- package/lib/revision-regression-review.js.map +1 -0
- package/lib/revision-review.d.ts +242 -0
- package/lib/revision-review.d.ts.map +1 -0
- package/lib/revision-review.js +600 -0
- package/lib/revision-review.js.map +1 -0
- package/lib/service.d.ts +138 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +878 -0
- package/lib/service.js.map +1 -0
- package/lib/source-review-git.d.ts +32 -0
- package/lib/source-review-git.d.ts.map +1 -0
- package/lib/source-review-git.js +241 -0
- package/lib/source-review-git.js.map +1 -0
- package/lib/source-review-native.d.ts +27 -0
- package/lib/source-review-native.d.ts.map +1 -0
- package/lib/source-review-native.js +149 -0
- package/lib/source-review-native.js.map +1 -0
- package/lib/source-review-store.d.ts +44 -0
- package/lib/source-review-store.d.ts.map +1 -0
- package/lib/source-review-store.js +212 -0
- package/lib/source-review-store.js.map +1 -0
- package/lib/source-review.d.ts +86 -0
- package/lib/source-review.d.ts.map +1 -0
- package/lib/source-review.js +255 -0
- package/lib/source-review.js.map +1 -0
- package/lib/store.d.ts +84 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/store.js +386 -0
- package/lib/store.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/package.json +144 -3
- package/runtime/plugin-observer-launcher.c +246 -0
package/lib/service.js
ADDED
|
@@ -0,0 +1,878 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isAbsolute, normalize, resolve } from 'node:path';
|
|
3
|
+
import { Context, Service } from '@deepseek-ai/cordis';
|
|
4
|
+
import { acceptanceCanonicalJson, acceptanceDigest, acceptanceProtocolForTask, createTaskAcceptanceContract, createTaskVerificationReceipt, } from '@dsh-ray/task-acceptance-contract';
|
|
5
|
+
import { Config, assertCriteriaDecidable, compileAcceptanceProfiles } from './config.js';
|
|
6
|
+
import { verifyAcceptanceCriteria } from './drivers.js';
|
|
7
|
+
import { AcceptanceStore } from './store.js';
|
|
8
|
+
import { SourceReviewRuntime, validateSourceReviewConfig } from './source-review.js';
|
|
9
|
+
import { MemoryReviewRuntime, validateMemoryReviewConfig } from './memory-review.js';
|
|
10
|
+
import { CreationReviewRuntime, validateCreationReviewConfig } from './creation-review.js';
|
|
11
|
+
import { RevisionReviewRuntime, validateRevisionReviewConfig } from './revision-review.js';
|
|
12
|
+
import { RevisionRegressionReviewRuntime, validateRevisionRegressionReviewConfig } from './revision-regression-review.js';
|
|
13
|
+
export { Config } from './config.js';
|
|
14
|
+
const producerNames = ['assistantAutomations', 'assistantDelivery', 'assistantGoals'];
|
|
15
|
+
const producerTaskKinds = Object.freeze({
|
|
16
|
+
assistantAutomations: ['automation-run'], assistantDelivery: ['foreground-turn'], assistantGoals: ['goal-step', 'goal-outcome'],
|
|
17
|
+
});
|
|
18
|
+
const PROFILE_SELECTION_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/u;
|
|
19
|
+
const PREPARED_PROFILE_ID = 'owner-prepared';
|
|
20
|
+
const PREPARED_PROFILE_VERSION = 1;
|
|
21
|
+
/**
|
|
22
|
+
* Prepared profiles derive from the sealed criteria and bounds alone. That lets
|
|
23
|
+
* a restart re-verify a seal from the stored contract without another table,
|
|
24
|
+
* while static config profiles keep their own digests.
|
|
25
|
+
*/
|
|
26
|
+
const preparedProfileDigest = (criteria, bounds) => acceptanceDigest({ protocol: 'assistant-goals/prepared-profile/v1', criteria, bounds });
|
|
27
|
+
const PROFILE_SELECTION_PRESET = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
|
|
28
|
+
function record(value, keys, label) {
|
|
29
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)
|
|
30
|
+
|| (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
|
|
31
|
+
|| Reflect.ownKeys(value).some(key => typeof key !== 'string')
|
|
32
|
+
|| Object.getOwnPropertyNames(value).sort().join(',') !== [...keys].sort().join(',')
|
|
33
|
+
|| Object.values(Object.getOwnPropertyDescriptors(value)).some(property => !property.enumerable || !('value' in property))) {
|
|
34
|
+
throw new Error(`assistant-verifier: invalid ${label} selection`);
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function selectionKey(value) {
|
|
39
|
+
const selection = record(value, ['scope', 'owner', 'objective', 'taskKind'], 'profile');
|
|
40
|
+
const scope = record(selection.scope, ['workspace', 'preset'], 'profile scope');
|
|
41
|
+
const owner = record(selection.owner, ['principalRecordId', 'principalVersion'], 'profile owner');
|
|
42
|
+
if (typeof scope.workspace !== 'string' || scope.workspace.includes('\0') || Buffer.byteLength(scope.workspace) > 4_096
|
|
43
|
+
|| scope.workspace !== scope.workspace.normalize('NFC').trim() || !isAbsolute(scope.workspace)
|
|
44
|
+
|| normalize(scope.workspace) !== scope.workspace || resolve(scope.workspace) !== scope.workspace
|
|
45
|
+
|| typeof scope.preset !== 'string' || !PROFILE_SELECTION_PRESET.test(scope.preset)
|
|
46
|
+
|| typeof owner.principalRecordId !== 'string' || !PROFILE_SELECTION_ID.test(owner.principalRecordId)
|
|
47
|
+
|| typeof owner.principalVersion !== 'number'
|
|
48
|
+
|| !Number.isSafeInteger(owner.principalVersion) || owner.principalVersion < 1
|
|
49
|
+
|| typeof selection.objective !== 'string' || selection.objective === '' || selection.objective.includes('\0') || Buffer.byteLength(selection.objective) > 65_536
|
|
50
|
+
|| (selection.taskKind !== 'automation-run' && selection.taskKind !== 'foreground-turn'
|
|
51
|
+
&& selection.taskKind !== 'goal-step' && selection.taskKind !== 'goal-outcome')) {
|
|
52
|
+
throw new Error('assistant-verifier: invalid profile selection');
|
|
53
|
+
}
|
|
54
|
+
return acceptanceCanonicalJson([scope, owner, selection.taskKind, selection.objective]);
|
|
55
|
+
}
|
|
56
|
+
function objectivesSelectionKey(value) {
|
|
57
|
+
const selection = record(value, ['scope', 'owner', 'taskKind'], 'profile');
|
|
58
|
+
const scope = record(selection.scope, ['workspace', 'preset'], 'profile scope');
|
|
59
|
+
const owner = record(selection.owner, ['principalRecordId', 'principalVersion'], 'profile owner');
|
|
60
|
+
if (typeof scope.workspace !== 'string' || scope.workspace.includes('\0') || Buffer.byteLength(scope.workspace) > 4_096
|
|
61
|
+
|| scope.workspace !== scope.workspace.normalize('NFC').trim() || !isAbsolute(scope.workspace)
|
|
62
|
+
|| normalize(scope.workspace) !== scope.workspace || resolve(scope.workspace) !== scope.workspace
|
|
63
|
+
|| typeof scope.preset !== 'string' || !PROFILE_SELECTION_PRESET.test(scope.preset)
|
|
64
|
+
|| typeof owner.principalRecordId !== 'string' || !PROFILE_SELECTION_ID.test(owner.principalRecordId)
|
|
65
|
+
|| typeof owner.principalVersion !== 'number'
|
|
66
|
+
|| !Number.isSafeInteger(owner.principalVersion) || owner.principalVersion < 1
|
|
67
|
+
|| (selection.taskKind !== 'automation-run' && selection.taskKind !== 'foreground-turn'
|
|
68
|
+
&& selection.taskKind !== 'goal-step' && selection.taskKind !== 'goal-outcome')) {
|
|
69
|
+
throw new Error('assistant-verifier: invalid profile selection');
|
|
70
|
+
}
|
|
71
|
+
return acceptanceCanonicalJson([scope, owner, selection.taskKind]);
|
|
72
|
+
}
|
|
73
|
+
function freeze(value) {
|
|
74
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
75
|
+
for (const key of Reflect.ownKeys(value))
|
|
76
|
+
freeze(value[key]);
|
|
77
|
+
Object.freeze(value);
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function profileCopy(profile) {
|
|
82
|
+
return freeze(structuredClone(profile));
|
|
83
|
+
}
|
|
84
|
+
/** Sanitized entry for one installed authority; never credentials or environment. */
|
|
85
|
+
function authorityCatalogEntry(authority) {
|
|
86
|
+
switch (authority.kind) {
|
|
87
|
+
case 'runner': return freeze({ id: authority.id, digest: authority.digest, kind: 'runner',
|
|
88
|
+
artifactPath: 'workspace-relative',
|
|
89
|
+
note: 'process-behavior artifactPath must be a workspace-relative path; expected stdout and exit code are compared with this fixed runner executable.' });
|
|
90
|
+
case 'isolated-runner': return freeze({ id: authority.id, digest: authority.digest, kind: 'isolated-runner',
|
|
91
|
+
artifactPath: 'workspace-relative',
|
|
92
|
+
testSetIds: Object.freeze(authority.testSets.map(testSet => testSet.id)),
|
|
93
|
+
note: 'isolated-process-behavior criteria bind exactly one testSetId from this list.' });
|
|
94
|
+
case 'document': return freeze({ id: authority.id, digest: authority.digest, kind: 'document',
|
|
95
|
+
sourceIds: Object.freeze(authority.sources.map(source => source.id)),
|
|
96
|
+
note: 'document-citations requiredText quotes may cite these source ids; case URLs stay inside the verifier.' });
|
|
97
|
+
case 'readback': return freeze({ id: authority.id, digest: authority.digest, kind: 'readback',
|
|
98
|
+
objectIdPointer: authority.objectIdPointer,
|
|
99
|
+
note: 'target-readback objectId is a Host-configured object id resolved through this JSON pointer.' });
|
|
100
|
+
case 'repository-readback':
|
|
101
|
+
case 'repository-commit-readback': return freeze({ id: authority.id, digest: authority.digest, kind: authority.kind,
|
|
102
|
+
objectId: `${authority.repository}:${authority.branch}`,
|
|
103
|
+
note: 'target-readback objectId must be exactly "<repository>:<branch>" as shown; expected pointers use the readback response shape.' });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function isProducer(value) {
|
|
107
|
+
const item = value;
|
|
108
|
+
return item !== null && typeof item === 'object'
|
|
109
|
+
&& typeof item.trustedAcceptanceProducerGeneration === 'function'
|
|
110
|
+
&& typeof item.registerTaskAcceptanceSink === 'function'
|
|
111
|
+
&& typeof item.inspectAcceptedExecution === 'function';
|
|
112
|
+
}
|
|
113
|
+
/** Host-only verification. There is intentionally no model trusted-write tool. */
|
|
114
|
+
export class AssistantVerifierService extends Service {
|
|
115
|
+
static Config = Config;
|
|
116
|
+
#store;
|
|
117
|
+
#compiled;
|
|
118
|
+
#bindings = new Map();
|
|
119
|
+
#registrations = new WeakSet();
|
|
120
|
+
#isolatedRunners = new Map();
|
|
121
|
+
#generation = randomUUID();
|
|
122
|
+
#workerId = `verifier-${randomUUID()}`;
|
|
123
|
+
#controller = new AbortController();
|
|
124
|
+
#now;
|
|
125
|
+
#requireAcceptance;
|
|
126
|
+
#evaluation;
|
|
127
|
+
#running;
|
|
128
|
+
#awaitingCursor = '';
|
|
129
|
+
#outboxCursor = '';
|
|
130
|
+
#active = true;
|
|
131
|
+
#sourceReviewer;
|
|
132
|
+
#sourceReviewers = new Set();
|
|
133
|
+
#memoryReviewer;
|
|
134
|
+
#memoryReviewConfig;
|
|
135
|
+
#memoryReviewers = new Set();
|
|
136
|
+
#creationReviewer;
|
|
137
|
+
#creationReviewers = new Set();
|
|
138
|
+
#revisionReviewer;
|
|
139
|
+
#revisionReviewers = new Set();
|
|
140
|
+
#revisionRegressionReviewer;
|
|
141
|
+
#revisionRegressionReviewers = new Set();
|
|
142
|
+
constructor(ctx, config, options = {}) {
|
|
143
|
+
super(ctx, 'assistantVerifier');
|
|
144
|
+
const normalized = Config(config);
|
|
145
|
+
const sourceReviews = normalized.sourceReviews === undefined ? undefined : validateSourceReviewConfig(normalized.sourceReviews);
|
|
146
|
+
const memoryReviews = normalized.memoryReviews === undefined ? undefined : validateMemoryReviewConfig(normalized.memoryReviews);
|
|
147
|
+
const creationReviews = normalized.creationReviews === undefined ? undefined : validateCreationReviewConfig(normalized.creationReviews);
|
|
148
|
+
const revisionReviews = normalized.revisionReviews === undefined ? undefined : validateRevisionReviewConfig(normalized.revisionReviews);
|
|
149
|
+
const revisionRegressions = normalized.revisionRegressions === undefined ? undefined
|
|
150
|
+
: validateRevisionRegressionReviewConfig(normalized.revisionRegressions);
|
|
151
|
+
this.#memoryReviewConfig = memoryReviews;
|
|
152
|
+
this.#compiled = compileAcceptanceProfiles(normalized);
|
|
153
|
+
this.#now = options.now ?? Date.now;
|
|
154
|
+
this.#requireAcceptance = normalized.requireAcceptance ?? true;
|
|
155
|
+
this.#store = new AcceptanceStore(normalized.databasePath);
|
|
156
|
+
for (const name of producerNames) {
|
|
157
|
+
const current = ctx.get(name);
|
|
158
|
+
if (isProducer(current))
|
|
159
|
+
this.#bind(name, current);
|
|
160
|
+
ctx.inject([name], injected => {
|
|
161
|
+
const producer = injected.get(name);
|
|
162
|
+
if (isProducer(producer))
|
|
163
|
+
return this.#bind(name, producer);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
const interval = normalized.tickIntervalMs ?? 5_000;
|
|
167
|
+
const timer = interval === 0 ? undefined : setInterval(() => {
|
|
168
|
+
void this.tick().catch(error => {
|
|
169
|
+
ctx.logger.warn('assistant-verifier reconciliation failed: %s', error instanceof Error ? error.message : 'unknown');
|
|
170
|
+
});
|
|
171
|
+
}, interval);
|
|
172
|
+
timer?.unref?.();
|
|
173
|
+
ctx.effect(() => async () => {
|
|
174
|
+
this.#active = false;
|
|
175
|
+
this.#controller.abort(new Error('assistant-verifier disposed'));
|
|
176
|
+
if (timer !== undefined)
|
|
177
|
+
clearInterval(timer);
|
|
178
|
+
for (const binding of this.#bindings.values())
|
|
179
|
+
binding.dispose();
|
|
180
|
+
this.#evaluation = undefined;
|
|
181
|
+
// Abort both review lanes before awaiting unrelated acceptance teardown.
|
|
182
|
+
const reviews = [...this.#sourceReviewers, ...this.#memoryReviewers, ...this.#creationReviewers,
|
|
183
|
+
...this.#revisionReviewers, ...this.#revisionRegressionReviewers].map(reviewer => reviewer.close());
|
|
184
|
+
await this.#running?.catch(() => { });
|
|
185
|
+
await Promise.allSettled([...this.#isolatedRunners.values()].map(async (runner) => (await runner).close()));
|
|
186
|
+
await Promise.allSettled(reviews);
|
|
187
|
+
this.#store.close();
|
|
188
|
+
}, 'assistant-verifier.database');
|
|
189
|
+
if (sourceReviews)
|
|
190
|
+
ctx.inject(['agents', 'sessions', 'tools', 'llm', 'systemPrompt', 'assistantPolicy'], injected => {
|
|
191
|
+
injected.effect(() => {
|
|
192
|
+
if (!this.#active)
|
|
193
|
+
return () => { };
|
|
194
|
+
const reviewer = new SourceReviewRuntime(injected, sourceReviews, normalized.databasePath);
|
|
195
|
+
this.#sourceReviewer = reviewer;
|
|
196
|
+
this.#sourceReviewers.add(reviewer);
|
|
197
|
+
return async () => {
|
|
198
|
+
if (this.#sourceReviewer === reviewer)
|
|
199
|
+
this.#sourceReviewer = undefined;
|
|
200
|
+
await reviewer.close();
|
|
201
|
+
this.#sourceReviewers.delete(reviewer);
|
|
202
|
+
};
|
|
203
|
+
}, 'assistant-verifier.source-review');
|
|
204
|
+
});
|
|
205
|
+
if (memoryReviews)
|
|
206
|
+
ctx.inject(['agents', 'sessions', 'tools', 'llm', 'systemPrompt', 'assistantPolicy', 'assistantDelivery', 'assistantEvaluation'], injected => {
|
|
207
|
+
injected.effect(() => {
|
|
208
|
+
if (!this.#active)
|
|
209
|
+
return () => { };
|
|
210
|
+
const reviewer = new MemoryReviewRuntime(injected, memoryReviews, normalized.databasePath);
|
|
211
|
+
this.#memoryReviewer = reviewer;
|
|
212
|
+
this.#memoryReviewers.add(reviewer);
|
|
213
|
+
return async () => {
|
|
214
|
+
if (this.#memoryReviewer === reviewer)
|
|
215
|
+
this.#memoryReviewer = undefined;
|
|
216
|
+
await reviewer.close();
|
|
217
|
+
this.#memoryReviewers.delete(reviewer);
|
|
218
|
+
};
|
|
219
|
+
}, 'assistant-verifier.memory-review');
|
|
220
|
+
});
|
|
221
|
+
if (creationReviews)
|
|
222
|
+
ctx.inject(['agents', 'sessions', 'tools', 'llm', 'systemPrompt', 'assistantPolicy', 'pluginControlPlane'], injected => {
|
|
223
|
+
injected.effect(() => {
|
|
224
|
+
if (!this.#active)
|
|
225
|
+
return () => { };
|
|
226
|
+
const reviewer = new CreationReviewRuntime(injected, creationReviews, normalized.databasePath);
|
|
227
|
+
this.#creationReviewer = reviewer;
|
|
228
|
+
this.#creationReviewers.add(reviewer);
|
|
229
|
+
return async () => {
|
|
230
|
+
if (this.#creationReviewer === reviewer)
|
|
231
|
+
this.#creationReviewer = undefined;
|
|
232
|
+
await reviewer.close();
|
|
233
|
+
this.#creationReviewers.delete(reviewer);
|
|
234
|
+
};
|
|
235
|
+
}, 'assistant-verifier.creation-review');
|
|
236
|
+
});
|
|
237
|
+
if (revisionReviews)
|
|
238
|
+
ctx.inject(['agents', 'sessions', 'tools', 'llm', 'systemPrompt', 'assistantPolicy', 'pluginControlPlane'], injected => {
|
|
239
|
+
injected.effect(() => {
|
|
240
|
+
if (!this.#active)
|
|
241
|
+
return () => { };
|
|
242
|
+
const reviewer = new RevisionReviewRuntime(injected, revisionReviews, normalized.databasePath);
|
|
243
|
+
this.#revisionReviewer = reviewer;
|
|
244
|
+
this.#revisionReviewers.add(reviewer);
|
|
245
|
+
return async () => {
|
|
246
|
+
if (this.#revisionReviewer === reviewer)
|
|
247
|
+
this.#revisionReviewer = undefined;
|
|
248
|
+
await reviewer.close();
|
|
249
|
+
this.#revisionReviewers.delete(reviewer);
|
|
250
|
+
};
|
|
251
|
+
}, 'assistant-verifier.revision-review');
|
|
252
|
+
});
|
|
253
|
+
if (revisionRegressions)
|
|
254
|
+
ctx.inject(['pluginControlPlane'], injected => {
|
|
255
|
+
injected.effect(() => {
|
|
256
|
+
if (!this.#active)
|
|
257
|
+
return () => { };
|
|
258
|
+
const reviewer = new RevisionRegressionReviewRuntime(injected, revisionRegressions, normalized.databasePath, parent => this.#creationReviewer?.readRetainedCases(parent));
|
|
259
|
+
this.#revisionRegressionReviewer = reviewer;
|
|
260
|
+
this.#revisionRegressionReviewers.add(reviewer);
|
|
261
|
+
return async () => {
|
|
262
|
+
if (this.#revisionRegressionReviewer === reviewer)
|
|
263
|
+
this.#revisionRegressionReviewer = undefined;
|
|
264
|
+
await reviewer.close();
|
|
265
|
+
this.#revisionRegressionReviewers.delete(reviewer);
|
|
266
|
+
};
|
|
267
|
+
}, 'assistant-verifier.revision-regression-review');
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
/** Frozen public acceptance authority; unavailable until the private Host peers are active. */
|
|
271
|
+
inspectCreationAcceptanceAuthority = (input) => {
|
|
272
|
+
this.#assertActive();
|
|
273
|
+
return this.#creationReviewer?.inspect(input);
|
|
274
|
+
};
|
|
275
|
+
/** Pure, current WorkItem creation reviewer capability; never allocates a runner or claim. */
|
|
276
|
+
inspectWorkItemCreationReviewReadiness = () => {
|
|
277
|
+
if (!this.#active)
|
|
278
|
+
return undefined;
|
|
279
|
+
return this.#creationReviewer?.inspectWorkItemCreationReviewReadiness();
|
|
280
|
+
};
|
|
281
|
+
/** Private Host continuation only. Source, artifact and owner are re-read through Control Plane. */
|
|
282
|
+
verifyPluginCreation = (request, signal) => {
|
|
283
|
+
this.#assertActive();
|
|
284
|
+
return this.#creationReviewer?.run(request, signal)
|
|
285
|
+
?? Promise.resolve({ status: 'unknown', reason: 'verification-unavailable' });
|
|
286
|
+
};
|
|
287
|
+
/** Frozen revision authority; independent of the creation grant and quota. */
|
|
288
|
+
inspectRevisionAcceptanceAuthority = (input) => {
|
|
289
|
+
this.#assertActive();
|
|
290
|
+
return this.#revisionReviewer?.inspect(input);
|
|
291
|
+
};
|
|
292
|
+
/** Private Host continuation for a new task's candidate revision. It grants no execution authority. */
|
|
293
|
+
verifyPluginRevision = (request, signal) => {
|
|
294
|
+
this.#assertActive();
|
|
295
|
+
return this.#revisionReviewer?.run(request, signal)
|
|
296
|
+
?? Promise.resolve({ status: 'unknown', reason: 'verification-unavailable' });
|
|
297
|
+
};
|
|
298
|
+
/** Host-only parent behavior regression; no candidate execution or version switch authority. */
|
|
299
|
+
inspectRevisionRegressionAcceptanceAuthority = (input) => {
|
|
300
|
+
this.#assertActive();
|
|
301
|
+
return this.#revisionRegressionReviewer?.inspect(input);
|
|
302
|
+
};
|
|
303
|
+
verifyPluginRevisionRegression = (request, signal) => {
|
|
304
|
+
this.#assertActive();
|
|
305
|
+
return this.#revisionRegressionReviewer?.run(request, signal)
|
|
306
|
+
?? Promise.resolve({ status: 'unknown', reason: 'verification-unavailable' });
|
|
307
|
+
};
|
|
308
|
+
/** Host-only review. Source text and verdicts cannot be supplied by the caller. */
|
|
309
|
+
reviewMemoryLearning = (request, signal) => {
|
|
310
|
+
this.#assertActive();
|
|
311
|
+
if (!this.#memoryReviewer)
|
|
312
|
+
throw new Error('assistant-verifier: memory review services unavailable');
|
|
313
|
+
return this.#memoryReviewer.run(request, signal);
|
|
314
|
+
};
|
|
315
|
+
lookupMemoryLearningReview = (request) => {
|
|
316
|
+
this.#assertActive();
|
|
317
|
+
return this.#memoryReviewer?.lookup(request);
|
|
318
|
+
};
|
|
319
|
+
/** Host-only read of current authority and unclaimed review capacity. */
|
|
320
|
+
inspectMemoryLearningReviewAvailability = (input) => {
|
|
321
|
+
this.#assertActive();
|
|
322
|
+
const config = this.#memoryReviewConfig;
|
|
323
|
+
if (!config)
|
|
324
|
+
return undefined;
|
|
325
|
+
return this.#memoryReviewer?.inspectAvailability(input) ?? Object.freeze({ authorityId: config.authorityId,
|
|
326
|
+
authorityDigest: acceptanceDigest(config), expiresAt: config.expiresAt, remainingReviews: 0, available: false });
|
|
327
|
+
};
|
|
328
|
+
/** Host-only capability probe, including the exact decision directory. */
|
|
329
|
+
canReviewSourceRepair = (input) => this.#active && this.#sourceReviewer?.available(input) === true;
|
|
330
|
+
/** No model tool exposes this entry or the private decision writer. */
|
|
331
|
+
reviewSourceRepair = (input) => {
|
|
332
|
+
this.#assertActive();
|
|
333
|
+
if (!this.#sourceReviewer)
|
|
334
|
+
throw new Error('assistant-verifier: source review services unavailable');
|
|
335
|
+
return this.#sourceReviewer.run(input);
|
|
336
|
+
};
|
|
337
|
+
ownsTaskAcceptanceRegistration = (registration) => {
|
|
338
|
+
return this.#active && this.#registrations.has(registration);
|
|
339
|
+
};
|
|
340
|
+
trustedVerificationProducerGeneration = () => { this.#assertActive(); return this.#generation; };
|
|
341
|
+
/**
|
|
342
|
+
* Host-only configuration inspection for preflight. It never creates a
|
|
343
|
+
* contract, registers a producer, or authorizes/starts execution.
|
|
344
|
+
*/
|
|
345
|
+
supportsPreauthorizedGoalAcceptance = (selection) => {
|
|
346
|
+
const selected = this.inspectAcceptanceProfile(selection);
|
|
347
|
+
return selected !== null && ['goal-step', 'goal-outcome'].includes(selection.taskKind) && selected.profile.criteria.every(criterion => {
|
|
348
|
+
if (criterion.kind === 'isolated-process-behavior')
|
|
349
|
+
return true;
|
|
350
|
+
return selection.taskKind === 'goal-outcome' && criterion.kind === 'target-readback'
|
|
351
|
+
&& criterion.expected.some(value => value.pointer === '/ready' && value.value === true)
|
|
352
|
+
&& this.#compiled.authorities.some(authority => (authority.kind === 'repository-readback' || authority.kind === 'repository-commit-readback') && authority.id === criterion.authority.id && authority.digest === criterion.authority.digest && criterion.objectId === `${authority.repository}:${authority.branch}`);
|
|
353
|
+
});
|
|
354
|
+
};
|
|
355
|
+
/** Host-only binding: the caller cannot supply a contract, grant or replacement target. */
|
|
356
|
+
inspectRepositoryReadbackAuthority = (contractId, authorityId, authorityDigest) => {
|
|
357
|
+
this.#assertActive();
|
|
358
|
+
const contract = this.#store.getContract(contractId);
|
|
359
|
+
const authority = this.#compiled.authorities.find(item => item.id === authorityId && item.digest === authorityDigest);
|
|
360
|
+
if (!contract || contract.task.kind !== 'goal-outcome' || (authority?.kind !== 'repository-readback' && authority?.kind !== 'repository-commit-readback')
|
|
361
|
+
|| !contract.criteria.some(item => item.kind === 'target-readback' && item.authority.id === authorityId && item.authority.digest === authorityDigest && item.objectId === `${authority.repository}:${authority.branch}`)
|
|
362
|
+
|| contract.expiresAt <= this.#now())
|
|
363
|
+
throw new Error('assistant-verifier: repository acceptance binding unavailable');
|
|
364
|
+
return freeze({ contract, authority });
|
|
365
|
+
};
|
|
366
|
+
inspectAcceptanceProfile = (selection) => {
|
|
367
|
+
this.#assertActive();
|
|
368
|
+
const key = selectionKey(selection);
|
|
369
|
+
const selected = this.#compiled.profiles.find(({ profile }) => acceptanceCanonicalJson([
|
|
370
|
+
profile.scope, profile.owner, profile.taskKind, profile.objective,
|
|
371
|
+
]) === key);
|
|
372
|
+
return selected === undefined ? null : Object.freeze({
|
|
373
|
+
profile: profileCopy(selected.profile), digest: selected.digest,
|
|
374
|
+
});
|
|
375
|
+
};
|
|
376
|
+
/**
|
|
377
|
+
* Host-only objective discovery for preflight. It only returns configured
|
|
378
|
+
* objective text within the exact scope, owner, and task-kind boundary.
|
|
379
|
+
*/
|
|
380
|
+
inspectAcceptanceObjectives = (selection) => {
|
|
381
|
+
this.#assertActive();
|
|
382
|
+
const key = objectivesSelectionKey(selection);
|
|
383
|
+
return Object.freeze([...new Set(this.#compiled.profiles.flatMap(({ profile }) => acceptanceCanonicalJson([profile.scope, profile.owner, profile.taskKind]) === key ? [profile.objective] : []))]);
|
|
384
|
+
};
|
|
385
|
+
/**
|
|
386
|
+
* Host-only read-only catalog of installed acceptance authorities for one
|
|
387
|
+
* owner scope. It never registers a model tool, writes state, or exposes
|
|
388
|
+
* credentials, environment, executable/state paths or grant identities; the
|
|
389
|
+
* kind-specific bindings are guidance for constructing decidable criteria.
|
|
390
|
+
*/
|
|
391
|
+
inspectAcceptanceAuthorities = (input) => {
|
|
392
|
+
this.#assertActive();
|
|
393
|
+
const selection = record(input, ['scope', 'owner'], 'acceptance authority catalog');
|
|
394
|
+
const scope = record(selection.scope, ['workspace', 'preset'], 'acceptance authority catalog scope');
|
|
395
|
+
const owner = record(selection.owner, ['principalRecordId', 'principalVersion'], 'acceptance authority catalog owner');
|
|
396
|
+
if (typeof scope.workspace !== 'string' || scope.workspace.includes('\0') || Buffer.byteLength(scope.workspace) > 4_096
|
|
397
|
+
|| scope.workspace !== scope.workspace.normalize('NFC').trim() || !isAbsolute(scope.workspace)
|
|
398
|
+
|| normalize(scope.workspace) !== scope.workspace || resolve(scope.workspace) !== scope.workspace
|
|
399
|
+
|| typeof scope.preset !== 'string' || !PROFILE_SELECTION_PRESET.test(scope.preset)
|
|
400
|
+
|| typeof owner.principalRecordId !== 'string' || !PROFILE_SELECTION_ID.test(owner.principalRecordId)
|
|
401
|
+
|| typeof owner.principalVersion !== 'number' || !Number.isSafeInteger(owner.principalVersion) || owner.principalVersion < 1) {
|
|
402
|
+
throw new Error('assistant-verifier: invalid acceptance authority catalog selection');
|
|
403
|
+
}
|
|
404
|
+
return freeze({ protocol: 'assistant-verifier/acceptance-authorities/v1',
|
|
405
|
+
authorities: freeze(this.#compiled.authorities.map(authorityCatalogEntry)) });
|
|
406
|
+
};
|
|
407
|
+
registerTrustedVerifierEvaluationSink = (registration) => {
|
|
408
|
+
this.#assertActive();
|
|
409
|
+
const evaluation = this.ctx.get('assistantEvaluation', false);
|
|
410
|
+
if (registration.protocol !== 'assistant-verifier/evaluation/v1' || registration.generation !== this.#generation
|
|
411
|
+
|| typeof registration.append !== 'function'
|
|
412
|
+
|| typeof evaluation?.ownsTrustedVerifierEvaluationRegistration !== 'function'
|
|
413
|
+
|| evaluation.ownsTrustedVerifierEvaluationRegistration(registration) !== true
|
|
414
|
+
|| this.#evaluation !== undefined)
|
|
415
|
+
throw new Error('assistant-verifier: invalid Evaluation registration');
|
|
416
|
+
this.#evaluation = registration;
|
|
417
|
+
return () => { if (this.#evaluation === registration)
|
|
418
|
+
this.#evaluation = undefined; };
|
|
419
|
+
};
|
|
420
|
+
/** Inspection contains explicit pending work; an execution completion is not a success verdict. */
|
|
421
|
+
inspect = (contractId) => { this.#assertActive(); return this.#store.getState(contractId); };
|
|
422
|
+
/** Exact immutable contract plus its current validated state for Host feedback loops. */
|
|
423
|
+
inspectAcceptedTask = (contractId) => {
|
|
424
|
+
this.#assertActive();
|
|
425
|
+
const contract = this.#store.getContract(contractId);
|
|
426
|
+
const state = this.#store.getState(contractId);
|
|
427
|
+
return contract === null || state === null ? null : Object.freeze({ contract, ...state });
|
|
428
|
+
};
|
|
429
|
+
continuations = () => { this.#assertActive(); return this.#store.listAttention(); };
|
|
430
|
+
health = () => {
|
|
431
|
+
this.#assertActive();
|
|
432
|
+
return Object.freeze({ ready: true, profiles: this.#compiled.profiles.length,
|
|
433
|
+
requireAcceptance: this.#requireAcceptance,
|
|
434
|
+
hostProducers: Object.freeze([...this.#bindings.keys()].sort()),
|
|
435
|
+
evaluationConnected: this.#evaluation !== undefined,
|
|
436
|
+
...this.#store.counts(this.#now()) });
|
|
437
|
+
};
|
|
438
|
+
tick = () => {
|
|
439
|
+
this.#assertActive();
|
|
440
|
+
if (this.#running !== undefined)
|
|
441
|
+
return this.#running;
|
|
442
|
+
const promise = this.#tick();
|
|
443
|
+
this.#running = promise;
|
|
444
|
+
void promise.finally(() => { if (this.#running === promise)
|
|
445
|
+
this.#running = undefined; }).catch(() => { });
|
|
446
|
+
return promise;
|
|
447
|
+
};
|
|
448
|
+
#bind(name, producer) {
|
|
449
|
+
const generation = producer.trustedAcceptanceProducerGeneration();
|
|
450
|
+
const prior = this.#bindings.get(name);
|
|
451
|
+
if (prior?.generation === generation)
|
|
452
|
+
return prior.dispose;
|
|
453
|
+
if (typeof generation !== 'string' || generation.length < 1 || generation.length > 256)
|
|
454
|
+
throw new Error('assistant-verifier: invalid Host generation');
|
|
455
|
+
let live = true;
|
|
456
|
+
const handles = new WeakMap();
|
|
457
|
+
const current = () => {
|
|
458
|
+
this.#assertActive();
|
|
459
|
+
if (!live || this.#bindings.get(name)?.producer !== producer
|
|
460
|
+
|| this.#bindings.get(name)?.generation !== generation
|
|
461
|
+
|| producer.trustedAcceptanceProducerGeneration() !== generation)
|
|
462
|
+
throw new Error('assistant-verifier: stale Host registration');
|
|
463
|
+
};
|
|
464
|
+
const registration = Object.freeze({
|
|
465
|
+
protocol: 'assistant-verifier/host-producer/v1', generation, owner: this, requiresAcceptance: this.#requireAcceptance,
|
|
466
|
+
prepare: (input) => {
|
|
467
|
+
current();
|
|
468
|
+
if (!producerTaskKinds[name].includes(input.task.kind))
|
|
469
|
+
throw new Error('assistant-verifier: wrong Host task kind');
|
|
470
|
+
const accepted = this.#prepare(input);
|
|
471
|
+
if (accepted === null)
|
|
472
|
+
return null;
|
|
473
|
+
const handle = Object.freeze({ contractId: accepted.id, contractDigest: accepted.digest });
|
|
474
|
+
handles.set(handle, accepted);
|
|
475
|
+
return handle;
|
|
476
|
+
},
|
|
477
|
+
...(name === 'assistantGoals' ? { prepareOwnerContract: (input) => {
|
|
478
|
+
current();
|
|
479
|
+
const accepted = this.#prepareOwnerContract(input);
|
|
480
|
+
const handle = Object.freeze({ contractId: accepted.id, contractDigest: accepted.digest });
|
|
481
|
+
handles.set(handle, accepted);
|
|
482
|
+
return handle;
|
|
483
|
+
} } : {}),
|
|
484
|
+
prepareGoalAssessment: (input, template) => {
|
|
485
|
+
current();
|
|
486
|
+
if (name !== 'assistantGoals')
|
|
487
|
+
throw new Error('assistant-verifier: wrong Host assessment producer');
|
|
488
|
+
const accepted = this.#prepareGoalAssessment(input, template);
|
|
489
|
+
const handle = Object.freeze({ contractId: accepted.id, contractDigest: accepted.digest });
|
|
490
|
+
handles.set(handle, accepted);
|
|
491
|
+
return handle;
|
|
492
|
+
},
|
|
493
|
+
completed: async (handle) => {
|
|
494
|
+
current();
|
|
495
|
+
const contract = handles.get(handle);
|
|
496
|
+
if (contract === undefined)
|
|
497
|
+
throw new Error('assistant-verifier: foreign acceptance handle');
|
|
498
|
+
await this.#reconcileExecution(name, binding, contract);
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
this.#registrations.add(registration);
|
|
502
|
+
let detach;
|
|
503
|
+
const binding = { producer, generation, dispose: () => {
|
|
504
|
+
live = false;
|
|
505
|
+
this.#registrations.delete(registration);
|
|
506
|
+
if (this.#bindings.get(name) === binding)
|
|
507
|
+
this.#bindings.delete(name);
|
|
508
|
+
detach?.();
|
|
509
|
+
} };
|
|
510
|
+
this.#bindings.set(name, binding);
|
|
511
|
+
try {
|
|
512
|
+
detach = producer.registerTaskAcceptanceSink(registration);
|
|
513
|
+
if (typeof detach !== 'function')
|
|
514
|
+
throw new Error('assistant-verifier: Host registration lacks disposer');
|
|
515
|
+
}
|
|
516
|
+
catch (error) {
|
|
517
|
+
binding.dispose();
|
|
518
|
+
if (prior !== undefined)
|
|
519
|
+
this.#bindings.set(name, prior);
|
|
520
|
+
throw error;
|
|
521
|
+
}
|
|
522
|
+
prior?.dispose();
|
|
523
|
+
return binding.dispose;
|
|
524
|
+
}
|
|
525
|
+
#prepare(input) {
|
|
526
|
+
const match = acceptanceCanonicalJson([input.scope, input.owner, input.task.kind, input.objective]);
|
|
527
|
+
const selected = this.#compiled.profiles.find(({ profile }) => acceptanceCanonicalJson([
|
|
528
|
+
profile.scope, profile.owner, profile.taskKind, profile.objective,
|
|
529
|
+
]) === match);
|
|
530
|
+
const previous = this.#store.getTaskContract(input);
|
|
531
|
+
if (previous !== null) {
|
|
532
|
+
// A prepared seal is self-describing: re-derive its profile digest from the
|
|
533
|
+
// frozen criteria instead of requiring a matching static config profile.
|
|
534
|
+
const prepared = previous.profile.id === PREPARED_PROFILE_ID && previous.profile.version === PREPARED_PROFILE_VERSION
|
|
535
|
+
&& preparedProfileDigest(previous.criteria, previous.bounds) === previous.profile.digest;
|
|
536
|
+
if (acceptanceDigest(previous.task) !== acceptanceDigest(input.task) || previous.objective !== input.objective
|
|
537
|
+
|| (!prepared && selected?.digest !== previous.profile.digest)
|
|
538
|
+
|| previous.expiresAt <= this.#now())
|
|
539
|
+
throw new Error('assistant-verifier: accepted task changed or expired');
|
|
540
|
+
return previous;
|
|
541
|
+
}
|
|
542
|
+
if (selected === undefined) {
|
|
543
|
+
if (this.#requireAcceptance)
|
|
544
|
+
throw new Error('assistant-verifier: no Host-approved acceptance profile matches this exact task');
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
const now = this.#now();
|
|
548
|
+
return this.#store.accept(createTaskAcceptanceContract({ protocol: acceptanceProtocolForTask(input.task, selected.profile.criteria),
|
|
549
|
+
id: `acceptance-${acceptanceDigest([input.scope, input.owner, input.task])}`, ...input,
|
|
550
|
+
profile: { id: selected.profile.id, version: selected.profile.version, digest: selected.digest },
|
|
551
|
+
issuedAt: now, expiresAt: now + selected.profile.validityMs,
|
|
552
|
+
criteria: selected.profile.criteria, bounds: selected.profile.bounds }));
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Seal Host-prepared criteria for one owner goal. The contract carries a
|
|
556
|
+
* prepared profile digest instead of a configured profile, so the frozen
|
|
557
|
+
* criteria stay outside worker write authority; every criterion must be
|
|
558
|
+
* decidable by an authority this deployment actually installed.
|
|
559
|
+
*/
|
|
560
|
+
#prepareOwnerContract(input) {
|
|
561
|
+
const keys = ['scope', 'owner', 'task', 'objective', 'criteria', 'bounds', 'validityMs', 'preparer'].sort();
|
|
562
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)
|
|
563
|
+
|| Object.getOwnPropertyNames(input).sort().join(',') !== keys.join(',')) {
|
|
564
|
+
throw new Error('assistant-verifier: invalid owner-prepared contract input');
|
|
565
|
+
}
|
|
566
|
+
const { scope, owner, task, objective, criteria, bounds, validityMs, preparer } = input;
|
|
567
|
+
if (typeof objective !== 'string' || objective.trim().length === 0 || objective.length > 16_384) {
|
|
568
|
+
throw new Error('assistant-verifier: invalid owner-prepared objective');
|
|
569
|
+
}
|
|
570
|
+
if (task.kind !== 'goal-step' && task.kind !== 'goal-outcome') {
|
|
571
|
+
throw new Error('assistant-verifier: owner-prepared contracts require a goal task');
|
|
572
|
+
}
|
|
573
|
+
if (!Number.isSafeInteger(validityMs) || validityMs < 1_000 || validityMs > 86_400_000) {
|
|
574
|
+
throw new Error('assistant-verifier: invalid owner-prepared validity');
|
|
575
|
+
}
|
|
576
|
+
if (preparer === null || typeof preparer !== 'object' || Array.isArray(preparer)
|
|
577
|
+
|| Object.getOwnPropertyNames(preparer).sort().join(',') !== 'digest,id'
|
|
578
|
+
|| typeof preparer.id !== 'string' || !PROFILE_SELECTION_ID.test(preparer.id)
|
|
579
|
+
|| typeof preparer.digest !== 'string' || !/^[a-f0-9]{64}$/u.test(preparer.digest)) {
|
|
580
|
+
throw new Error('assistant-verifier: invalid owner-prepared preparer');
|
|
581
|
+
}
|
|
582
|
+
const profileDigest = preparedProfileDigest(criteria, bounds);
|
|
583
|
+
const previous = this.#store.getTaskContract({ scope, owner, task });
|
|
584
|
+
if (previous !== null) {
|
|
585
|
+
if (acceptanceDigest(previous.task) !== acceptanceDigest(task) || previous.objective !== objective
|
|
586
|
+
|| acceptanceDigest(previous.criteria) !== acceptanceDigest(criteria)
|
|
587
|
+
|| acceptanceDigest(previous.bounds) !== acceptanceDigest(bounds)
|
|
588
|
+
|| previous.profile.digest !== profileDigest) {
|
|
589
|
+
throw new Error('assistant-verifier: owner-prepared contract changed for this task');
|
|
590
|
+
}
|
|
591
|
+
if (previous.expiresAt <= this.#now())
|
|
592
|
+
throw new Error('assistant-verifier: owner-prepared contract expired');
|
|
593
|
+
return previous;
|
|
594
|
+
}
|
|
595
|
+
if (validityMs <= bounds.maxDurationMs) {
|
|
596
|
+
throw new Error('assistant-verifier: owner-prepared validity must exceed verification duration');
|
|
597
|
+
}
|
|
598
|
+
const now = this.#now();
|
|
599
|
+
const contract = createTaskAcceptanceContract({
|
|
600
|
+
protocol: acceptanceProtocolForTask(task, criteria),
|
|
601
|
+
id: `acceptance-${acceptanceDigest([scope, owner, task])}`,
|
|
602
|
+
scope, owner, task, objective,
|
|
603
|
+
profile: { id: 'owner-prepared', version: 1, digest: profileDigest },
|
|
604
|
+
issuedAt: now, expiresAt: now + validityMs, criteria, bounds,
|
|
605
|
+
});
|
|
606
|
+
// Fail closed before sealing: a criterion no installed authority can decide
|
|
607
|
+
// (wrong driver kind, missing isolated test set or repository object) must
|
|
608
|
+
// never reach a worker run.
|
|
609
|
+
assertCriteriaDecidable(contract, this.#compiled.authorities);
|
|
610
|
+
return this.#store.accept(contract);
|
|
611
|
+
}
|
|
612
|
+
#prepareGoalAssessment(input, template) {
|
|
613
|
+
const original = this.#store.getContract(template.contractId);
|
|
614
|
+
if (original?.digest !== template.contractDigest || original.task.kind !== 'goal-outcome'
|
|
615
|
+
|| input.task.kind !== 'goal-outcome')
|
|
616
|
+
throw new Error('assistant-verifier: invalid goal conditions template');
|
|
617
|
+
const identity = (task) => {
|
|
618
|
+
if (task.kind !== 'goal-outcome')
|
|
619
|
+
throw new Error('assistant-verifier: whole goal required');
|
|
620
|
+
const { assessmentId: _assessmentId, ...goal } = task.goal;
|
|
621
|
+
return goal;
|
|
622
|
+
};
|
|
623
|
+
if (acceptanceDigest([original.scope, original.owner, original.objective, identity(original.task)])
|
|
624
|
+
!== acceptanceDigest([input.scope, input.owner, input.objective, identity(input.task)])) {
|
|
625
|
+
throw new Error('assistant-verifier: goal assessment changed its definition or owner');
|
|
626
|
+
}
|
|
627
|
+
const selected = this.#compiled.profiles.find(({ digest }) => digest === original.profile.digest);
|
|
628
|
+
// Prepared goal conditions stay usable after a restart or a config change: the
|
|
629
|
+
// seal carries everything needed to re-derive its profile identity.
|
|
630
|
+
const prepared = original.profile.id === PREPARED_PROFILE_ID && original.profile.version === PREPARED_PROFILE_VERSION
|
|
631
|
+
&& preparedProfileDigest(original.criteria, original.bounds) === original.profile.digest;
|
|
632
|
+
const now = this.#now();
|
|
633
|
+
if ((!prepared && selected === undefined) || now + original.bounds.maxDurationMs >= original.expiresAt) {
|
|
634
|
+
throw new Error('assistant-verifier: original goal conditions unavailable or expired');
|
|
635
|
+
}
|
|
636
|
+
const previous = this.#store.getTaskContract(input);
|
|
637
|
+
if (previous !== null) {
|
|
638
|
+
if (acceptanceDigest(previous.task) !== acceptanceDigest(input.task) || previous.objective !== input.objective
|
|
639
|
+
|| acceptanceDigest([previous.profile, previous.criteria, previous.bounds, previous.expiresAt])
|
|
640
|
+
!== acceptanceDigest([original.profile, original.criteria, original.bounds, original.expiresAt])) {
|
|
641
|
+
throw new Error('assistant-verifier: goal assessment changed its frozen conditions');
|
|
642
|
+
}
|
|
643
|
+
return previous;
|
|
644
|
+
}
|
|
645
|
+
return this.#store.accept(createTaskAcceptanceContract({ protocol: acceptanceProtocolForTask(input.task, original.criteria),
|
|
646
|
+
id: `acceptance-${acceptanceDigest([input.scope, input.owner, input.task])}`, ...input,
|
|
647
|
+
profile: original.profile, criteria: original.criteria, bounds: original.bounds,
|
|
648
|
+
issuedAt: now, expiresAt: original.expiresAt }));
|
|
649
|
+
}
|
|
650
|
+
/** Resolve provenance through the live Host producer and its immutable step contract. */
|
|
651
|
+
#isolatedContext(binding) {
|
|
652
|
+
const current = () => {
|
|
653
|
+
this.#assertActive();
|
|
654
|
+
if (binding === undefined || this.#bindings.get('assistantGoals') !== binding
|
|
655
|
+
|| binding.producer.trustedAcceptanceProducerGeneration() !== binding.generation) {
|
|
656
|
+
throw new Error('assistant-verifier: artifact producer changed');
|
|
657
|
+
}
|
|
658
|
+
return binding.producer;
|
|
659
|
+
};
|
|
660
|
+
return {
|
|
661
|
+
readArtifact: async (contract, path) => {
|
|
662
|
+
if (contract.protocol !== 'task-acceptance/v4')
|
|
663
|
+
throw new Error('assistant-verifier: isolated contract required');
|
|
664
|
+
const producer = current();
|
|
665
|
+
const handle = await producer.inspectAcceptedArtifactSource?.(contract);
|
|
666
|
+
current();
|
|
667
|
+
const source = handle === undefined || handle === null ? null : this.#store.getContract(handle.contractId);
|
|
668
|
+
if (source === null || source.digest !== handle?.contractDigest || source.task.kind !== 'goal-step'
|
|
669
|
+
|| source.protocol !== 'task-acceptance/v4'
|
|
670
|
+
|| acceptanceDigest([source.scope, source.owner, source.objective]) !== acceptanceDigest([contract.scope, contract.owner, contract.objective])) {
|
|
671
|
+
throw new Error('assistant-verifier: artifact acceptance unavailable');
|
|
672
|
+
}
|
|
673
|
+
const definition = (task) => {
|
|
674
|
+
const { id, definitionVersion, definitionDigest, sessionId, nativeGoalId } = task.goal;
|
|
675
|
+
return { id, definitionVersion, definitionDigest, sessionId, nativeGoalId };
|
|
676
|
+
};
|
|
677
|
+
if (acceptanceDigest(definition(source.task)) !== acceptanceDigest(definition(contract.task))
|
|
678
|
+
|| contract.task.kind === 'goal-step' && source.digest !== contract.digest) {
|
|
679
|
+
throw new Error('assistant-verifier: artifact belongs to another goal');
|
|
680
|
+
}
|
|
681
|
+
const isolation = this.ctx.get('assistantIsolation', false);
|
|
682
|
+
if (typeof isolation?.readAcceptedArtifact !== 'function')
|
|
683
|
+
throw new Error('assistant-verifier: Isolation unavailable');
|
|
684
|
+
const artifact = isolation.readAcceptedArtifact(source, path);
|
|
685
|
+
current();
|
|
686
|
+
return artifact;
|
|
687
|
+
},
|
|
688
|
+
run: async (authority, key, artifact, stdin, signal) => {
|
|
689
|
+
current();
|
|
690
|
+
let pending = this.#isolatedRunners.get(authority.digest);
|
|
691
|
+
if (pending === undefined) {
|
|
692
|
+
pending = import('@dsh-ray/assistant-isolation').then(({ IsolatedVerifierRunner }) => {
|
|
693
|
+
this.#assertActive();
|
|
694
|
+
if (authority.backend !== 'linux-native') {
|
|
695
|
+
throw new Error('assistant-verifier: only the linux-native isolation backend is supported');
|
|
696
|
+
}
|
|
697
|
+
return new IsolatedVerifierRunner({ stateRoot: authority.stateRoot,
|
|
698
|
+
backend: 'linux-native', runtime: authority.runtime, cgroupRoots: authority.cgroupRoots,
|
|
699
|
+
authorityDigest: authority.digest, command: authority.command,
|
|
700
|
+
expiresAt: authority.expiresAt, maxRuns: authority.maxRuns, maxTotalDurationMs: authority.maxTotalDurationMs,
|
|
701
|
+
maxDurationMs: authority.maxDurationMs, maxOutputBytes: authority.maxOutputBytes });
|
|
702
|
+
});
|
|
703
|
+
this.#isolatedRunners.set(authority.digest, pending);
|
|
704
|
+
}
|
|
705
|
+
const runner = await pending;
|
|
706
|
+
current();
|
|
707
|
+
return runner.run(key, artifact, stdin, signal);
|
|
708
|
+
},
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async #reconcileExecution(name, binding, contract) {
|
|
712
|
+
const proof = await this.#bounded(binding.producer.inspectAcceptedExecution(contract), 5_000);
|
|
713
|
+
if (!this.#active || proof === null)
|
|
714
|
+
return;
|
|
715
|
+
if (this.#bindings.get(name) !== binding
|
|
716
|
+
|| binding.producer.trustedAcceptanceProducerGeneration() !== binding.generation) {
|
|
717
|
+
throw new Error('assistant-verifier: stale Host execution proof');
|
|
718
|
+
}
|
|
719
|
+
if (proof.contractId !== contract.id || proof.contractDigest !== contract.digest
|
|
720
|
+
|| proof.executionRef !== contract.task.ref
|
|
721
|
+
|| !Number.isSafeInteger(proof.dispatchedAt) || proof.dispatchedAt < contract.issuedAt
|
|
722
|
+
|| proof.completedAt < proof.dispatchedAt || proof.completedAt > this.#now()) {
|
|
723
|
+
throw new Error('assistant-verifier: actual execution does not bind prior acceptance');
|
|
724
|
+
}
|
|
725
|
+
this.#store.markExecutionFinished(contract.id, { status: proof.status, quiescent: proof.quiescent,
|
|
726
|
+
completedAt: proof.completedAt, executionRef: proof.executionRef });
|
|
727
|
+
}
|
|
728
|
+
async #tick() {
|
|
729
|
+
this.#store.expireAwaiting(this.#now());
|
|
730
|
+
let awaiting = this.#store.awaitingExecution(100, this.#awaitingCursor);
|
|
731
|
+
if (awaiting.length === 0 && this.#awaitingCursor !== '') {
|
|
732
|
+
this.#awaitingCursor = '';
|
|
733
|
+
awaiting = this.#store.awaitingExecution(100);
|
|
734
|
+
}
|
|
735
|
+
for (const contract of awaiting) {
|
|
736
|
+
this.#awaitingCursor = contract.id;
|
|
737
|
+
const name = contract.task.kind === 'automation-run'
|
|
738
|
+
? 'assistantAutomations'
|
|
739
|
+
: contract.task.kind === 'foreground-turn' ? 'assistantDelivery' : 'assistantGoals';
|
|
740
|
+
const binding = this.#bindings.get(name);
|
|
741
|
+
if (binding !== undefined)
|
|
742
|
+
await this.#reconcileExecution(name, binding, contract);
|
|
743
|
+
}
|
|
744
|
+
if (!this.#active)
|
|
745
|
+
return;
|
|
746
|
+
// One job per tick bounds both background load and work admitted during shutdown.
|
|
747
|
+
const claimed = this.#store.claimDue({ workerId: this.#workerId, now: this.#now(), leaseMs: 305_000 });
|
|
748
|
+
if (claimed !== null) {
|
|
749
|
+
const { contract, job, execution } = claimed;
|
|
750
|
+
const requiresLiveGoal = contract.task.kind === 'goal-outcome' || contract.protocol === 'task-acceptance/v4';
|
|
751
|
+
const outcomeBinding = requiresLiveGoal ? this.#bindings.get('assistantGoals') : undefined;
|
|
752
|
+
const startedAt = this.#now();
|
|
753
|
+
const unknown = (reason) => contract.criteria.map(criterion => ({
|
|
754
|
+
criterionId: criterion.id, status: 'unknown', reason, evidence: [],
|
|
755
|
+
}));
|
|
756
|
+
let results = unknown('verification-unavailable');
|
|
757
|
+
if (!execution.quiescent)
|
|
758
|
+
results = unknown('execution-not-quiescent');
|
|
759
|
+
else {
|
|
760
|
+
try {
|
|
761
|
+
results = await this.#bounded(verifyAcceptanceCriteria(contract, this.#compiled.authorities, this.#controller.signal, this.#isolatedContext(outcomeBinding), { read: async (accepted, authority, signal) => {
|
|
762
|
+
const reader = this.ctx.get('assistantActions', false);
|
|
763
|
+
if (typeof reader?.readRepositoryGoalOutcome !== 'function' || typeof reader.repositoryReadbackGeneration !== 'function')
|
|
764
|
+
throw new Error('repository broker unavailable');
|
|
765
|
+
const generation = reader.repositoryReadbackGeneration();
|
|
766
|
+
const result = await reader.readRepositoryGoalOutcome({ contractId: accepted.id, authorityId: authority.id, authorityDigest: authority.digest }, signal);
|
|
767
|
+
const current = this.ctx.get('assistantActions', false);
|
|
768
|
+
if (current?.repositoryReadbackGeneration() !== generation)
|
|
769
|
+
throw new Error('repository broker changed');
|
|
770
|
+
return result;
|
|
771
|
+
} }), contract.bounds.maxDurationMs);
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
results = unknown('verification-unavailable');
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
if (requiresLiveGoal && execution.quiescent) {
|
|
778
|
+
try {
|
|
779
|
+
if (outcomeBinding === undefined)
|
|
780
|
+
throw new Error('whole-goal producer unavailable');
|
|
781
|
+
const proof = await this.#bounded(outcomeBinding.producer.inspectAcceptedExecution(contract), 5_000);
|
|
782
|
+
if (this.#bindings.get('assistantGoals') !== outcomeBinding
|
|
783
|
+
|| outcomeBinding.producer.trustedAcceptanceProducerGeneration() !== outcomeBinding.generation
|
|
784
|
+
|| proof === null || proof.contractId !== contract.id || proof.contractDigest !== contract.digest
|
|
785
|
+
|| proof.dispatchedAt < contract.issuedAt || proof.dispatchedAt > execution.completedAt
|
|
786
|
+
|| acceptanceDigest({ status: proof.status, quiescent: proof.quiescent, completedAt: proof.completedAt, executionRef: proof.executionRef }) !== acceptanceDigest(execution)) {
|
|
787
|
+
throw new Error('whole-goal assessment authority changed');
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
catch {
|
|
791
|
+
results = unknown('whole-goal-assessment-authority-changed');
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (!this.#active || this.#controller.signal.aborted)
|
|
795
|
+
return;
|
|
796
|
+
const now = this.#now();
|
|
797
|
+
let receipt = null;
|
|
798
|
+
if (now < contract.expiresAt && now >= startedAt) {
|
|
799
|
+
const payload = { protocol: contract.protocol === 'task-acceptance/v4' ? 'task-verification/v4' : contract.protocol === 'task-acceptance/v3' ? 'task-verification/v3' : contract.protocol === 'task-acceptance/v2' ? 'task-verification/v2' : 'task-verification/v1', id: `verification-${contract.id}-${job.fencingToken}`,
|
|
800
|
+
contractId: contract.id, contractDigest: contract.digest, scope: contract.scope, owner: contract.owner,
|
|
801
|
+
task: contract.task, results, startedAt, completedAt: now, validUntil: Math.min(contract.expiresAt, ...contract.criteria.flatMap(criterion => {
|
|
802
|
+
const authority = this.#compiled.authorities.find(item => item.id === criterion.authority.id && item.digest === criterion.authority.digest);
|
|
803
|
+
return authority?.kind === 'repository-readback' || authority?.kind === 'repository-commit-readback' ? [startedAt + authority.freshnessMs] : [];
|
|
804
|
+
})) };
|
|
805
|
+
try {
|
|
806
|
+
receipt = createTaskVerificationReceipt(contract, payload);
|
|
807
|
+
}
|
|
808
|
+
catch {
|
|
809
|
+
try {
|
|
810
|
+
receipt = createTaskVerificationReceipt(contract, { ...payload, results: unknown('evidence-invalid-or-oversize') });
|
|
811
|
+
}
|
|
812
|
+
catch { /* A budget too small even for unknown evidence cannot mint a receipt. */ }
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
this.#store.finish({ contractId: contract.id, workerId: this.#workerId, fencingToken: job.fencingToken,
|
|
816
|
+
now, receipt, reason: receipt?.objectiveStatus === 'achieved' ? 'verified' : receipt?.objectiveStatus ?? 'contract-expired',
|
|
817
|
+
...(execution.quiescent && (receipt === null || receipt.objectiveStatus === 'unknown') ? { retryAt: now + 5_000 * job.attempt } : {}) });
|
|
818
|
+
if (receipt !== null) {
|
|
819
|
+
try {
|
|
820
|
+
this.ctx.emit('assistant-verifier/receipt', Object.freeze({ contractId: contract.id, contractDigest: contract.digest, receiptId: receipt.id, receiptDigest: receipt.digest, taskKind: contract.task.kind }));
|
|
821
|
+
}
|
|
822
|
+
catch { /* A best-effort nudge must not interrupt the durable Evaluation outbox. */ }
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
let pendingReceipts = this.#store.pendingReceipts(100, this.#outboxCursor);
|
|
826
|
+
if (pendingReceipts.length === 0 && this.#outboxCursor !== '') {
|
|
827
|
+
this.#outboxCursor = '';
|
|
828
|
+
pendingReceipts = this.#store.pendingReceipts(100);
|
|
829
|
+
}
|
|
830
|
+
for (const pending of pendingReceipts) {
|
|
831
|
+
if (!this.#active)
|
|
832
|
+
return;
|
|
833
|
+
const sink = this.#evaluation;
|
|
834
|
+
if (sink === undefined)
|
|
835
|
+
return;
|
|
836
|
+
this.#outboxCursor = pending.receipt.id;
|
|
837
|
+
// Expired deliveries remain visible in the outbox; they never acquire fresh authority.
|
|
838
|
+
if (pending.receipt.validUntil <= this.#now())
|
|
839
|
+
continue;
|
|
840
|
+
const execution = this.#store.getState(pending.contract.id)?.execution;
|
|
841
|
+
if (execution === null || execution === undefined)
|
|
842
|
+
throw new Error('assistant-verifier: receipt lost execution binding');
|
|
843
|
+
await this.#bounded(sink.append({ ...pending, execution }), 5_000);
|
|
844
|
+
if (this.#evaluation !== sink || !this.#active)
|
|
845
|
+
return;
|
|
846
|
+
this.#store.acknowledgeReceipt(pending.receipt.id, pending.receipt.digest);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/** Stop waiting on an unavailable Host without granting late results authority. */
|
|
850
|
+
#bounded(operation, timeoutMs) {
|
|
851
|
+
return new Promise((resolve, reject) => {
|
|
852
|
+
let settled = false;
|
|
853
|
+
const signal = this.#controller.signal;
|
|
854
|
+
const finish = (error, value) => {
|
|
855
|
+
if (settled)
|
|
856
|
+
return;
|
|
857
|
+
settled = true;
|
|
858
|
+
clearTimeout(timer);
|
|
859
|
+
signal.removeEventListener('abort', abort);
|
|
860
|
+
if (error !== undefined)
|
|
861
|
+
reject(error);
|
|
862
|
+
else
|
|
863
|
+
resolve(value);
|
|
864
|
+
};
|
|
865
|
+
const abort = () => finish(new Error('assistant-verifier: operation cancelled'));
|
|
866
|
+
const timer = setTimeout(() => finish(new Error('assistant-verifier: Host operation deadline exceeded')), timeoutMs);
|
|
867
|
+
timer.unref?.();
|
|
868
|
+
operation.then(value => finish(undefined, value), error => finish(error instanceof Error ? error : new Error('assistant-verifier: Host operation failed')));
|
|
869
|
+
if (signal.aborted)
|
|
870
|
+
abort();
|
|
871
|
+
else
|
|
872
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
#assertActive() { if (!this.#active)
|
|
876
|
+
throw new Error('assistant-verifier: disposed'); }
|
|
877
|
+
}
|
|
878
|
+
//# sourceMappingURL=service.js.map
|